I’m having an issue with db.collection.aggregate in a MongoDB function where the results returned to me is missing the _id, it’s just blank. It’s a simple aggregate, with a $lookup, $match, and a $project, but anything I’ve tried to actually output the _id in the results is failing.
here is a simple example of the schema and query I’m doing this with…
a_collection:
{
_id : ObjectId(‘63f381b50ee158b55cc82b1a’),
a_name : ‘This is an example’,
b_tags: [
ObjectId(‘640624f7dace963b6d2865c3’),
ObjectId(‘640624f7dace963b6d2865c4’),
ObjectId(‘640624f7dace963b6d2865c5’),
]
}
b_collection:
{
{
_id: ObjectId(‘640624f7dace963b6d2865c3’),
b_tag : 'This',
},
{
_id: ObjectId(‘640624f7dace963b6d2865c4’),
b_tag : 'demo',
},
{
_id: ObjectId(‘640624f7dace963b6d2865c5’),
b_tag : 'only',
},
}
My function is doing an aggregate to search in the joined table for a string passed in as a parameter.
var searchStr = 'demo';` // example string for matching
tagSearchQueryResult = await a_collection.aggregate([
{
// begin pipeline for
$lookup: {
"from": "b_collection",
"localField": "b_tags",
"foreignField": "b_tags._id",
"as": "b_tags",
"pipeline": [
{
"$addFields": { "b_tags": "$b_tags.b_tag" }
}
]
},
},
{
$match: {
$expr: { "$in": [ searchStr, "$b_tag" ] }
},
},
{
"$project": {
"id": "$_id" ,
"a_name": 1,
}
}
]);
return { tagSearchQueryResult };
I do get back results as I expect, but without the _id of the document returned from the aggregate. I’m stumped why. I originally had foreignField: "_id"
for the $lookup, changed it to foreignField: "_b_tags._id"
thinking there was a conflict, but this did not fix the issue.
The results I’m returned look like this…
result (JavaScript):
EJSON.parse('{"tagSearchQueryResult":[{"_id”:{},”a_name”:”This is an example","id":{}}]}')
I’ve read and researched, found nothing that tells me what’s the cause.
Thanks.