我的db集合就像
{ "_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"
]
}
],
我需要输出
"example": [
{
"exId": "57f24ee56da92f9c19b0efd4",
"_id": "57f4cfa93eb5c694041fdf4c",
"projects": [
"57f4cfa83eb5c694041fdf45"
]
},
{
"exId" : "57f24ec16da92f9c19b0efcd",
"_id" : ObjectId("580864867a36f5bc1058c2c8"),
"projects" : [
"580864837a36f5bc1058c2a9",
"57f4c1303eb5c694041fdec6"
]
}
]
}
我的查询是
db.userDb.findOne({ '_id': req.params.userId }, { example: { $elemMatch: { exId: { $in: accIds } } } })
和accIds是一个包含值“57f24ec16da92f9c19b0efcd”的数组, “57f24ee56da92f9c19b0efd4” “57f24fa26da92f9c19b0f005”
但是我的输出是
"example": [
{
"exId": "57f24ee56da92f9c19b0efd4",
"_id": "57f4cfa93eb5c694041fdf4c",
"projects": [
"57f4cfa83eb5c694041fdf45"
]
}
],
感谢任何帮助
答案 0 :(得分:1)
db.collection.aggregate([
{ $unwind: '$example' },
{ $unwind: '$example.projects' },
{ $match: { 'example.exId': { $in: accIds} } },
{ $group: { _id: null, projectList: { $addToSet: '$example.projects' } } },
])
希望这会奏效。