In my mongodb query, I use $addFields to add ID field which concatenated of other three fields. My problem is that I get no result if I $match that new added field with value that I want to query. For other fields, they work just fine.
data = await model.aggregate([
{
$project: {
projectName: 1,
price: 1,
'document': '$$ROOT'
}
},
{
$addFields:{
'document.id': {$concat: ['$document.propertyId.prefix','$document.propertyId.number']}
}
},
{
$match: {
$and: [
{
$or: [
{id: {$regex: '.*' + req.query.search + '.*', $options: "i"}},
{projectName: {$regex: '.*' + req.query.search + '.*', $options: "i"}},
/*This also doesnt work*/
// {'document.id': {$regex: '.*' + req.query.search + '.*', $options: "i"}},
// {'document.projectName': {$regex: '.*' + req.query.search + '.*', $options: "i"}},
]
}
]
}
},
{
$replaceRoot: {newRoot: "$document"}
},
{
$sort: {
[sortBy]: sortType
}
},
]);
Next time please add a sample of your document so people can reproduce your problem. Having said that I don't see where your problem is. I created some data to reproduce your usecase. So I added the following document:
Then I executed your script (without the sort) and it works fine:
The fact that you get no results is probably due to your request parameters. Besides how can the
"projectName"
have the same search parameters as your"document.id"
Do they even match? Check your match pipeline again: