Reputation: 827
my db collection is like
{ "_id" : "57f4c1323eb5c694041ghea3",
"example" : [
{
"exId" : "57f4c0d43eb5c694041fdebd",
"_id" : ObjectId("57f4c1323eb5c694041fded2"),
"projects" : [
"57f4c1303eb5c694041fdec6"
]
},
{
"exId" : "57f24ee56da92f9c19b0efd4",
"_id" : ObjectId("57f4cfa93eb5c694041fdf4c"),
"projects" : [
"57f4cfa83eb5c694041fdf45"
]
},
{
"exId" : "57f24ec16da92f9c19b0efcd",
"_id" : ObjectId("580864867a36f5bc1058c2c8"),
"projects" : [
"580864837a36f5bc1058c2a9",
"57f4c1303eb5c694041fdec6"
]
}
],
I need to get output as
"example": [
{
"exId": "57f24ee56da92f9c19b0efd4",
"_id": "57f4cfa93eb5c694041fdf4c",
"projects": [
"57f4cfa83eb5c694041fdf45"
]
},
{
"exId" : "57f24ec16da92f9c19b0efcd",
"_id" : ObjectId("580864867a36f5bc1058c2c8"),
"projects" : [
"580864837a36f5bc1058c2a9",
"57f4c1303eb5c694041fdec6"
]
}
]
}
where my query is
db.userDb.findOne({ '_id': req.params.userId }, { example: { $elemMatch: { exId: { $in: accIds } } } })
and accIds is an array contains values "57f24ec16da92f9c19b0efcd", "57f24ee56da92f9c19b0efd4", "57f24fa26da92f9c19b0f005"
but my ouput is
"example": [
{
"exId": "57f24ee56da92f9c19b0efd4",
"_id": "57f4cfa93eb5c694041fdf4c",
"projects": [
"57f4cfa83eb5c694041fdf45"
]
}
],
any help is appreciated
Upvotes: 2
Views: 534
Reputation: 419
db.collection.aggregate([
{ $unwind: '$example' },
{ $unwind: '$example.projects' },
{ $match: { 'example.exId': { $in: accIds} } },
{ $group: { _id: null, projectList: { $addToSet: '$example.projects' } } },
])
Hope this will work.
Upvotes: 1