这个问题在这里已经有了答案:
$lookup on ObjectId's in an array
(6 个回答)
4年前关闭。
我正在尝试为文档中的嵌入式数组检索一些查找数据。以下是数据示例:
[
{
"_id": "58a4fa0e24180825b05e14e9",
"user_id": "589cf6511b94281f34617a13",
"user": {
"firstname": "John",
"lastname": "Doe"
},
"stages": [
{
"user_id": "589cf6511b94281f34617a13"
},
{
"user_id": "589cf6511b94281f346343c3"
}
],
}
]
如您所见,
stages
是一个数组,包含 user_id
仅限字段。这些都指向 _id
另一个名为 users
的集合中的字段.这是我得到上述结果的方式:
db.collection('things').aggregate([{
$match: finder
},
{
$lookup: {
from: 'users',
localField: 'user_id',
foreignField: '_id',
as: 'user'
}
},
{
$unwind: '$user'
}
]);
现在,这非常简单:选择记录,带有
user
字段查找 $lookup
.但是我怎么能对 stages
的元素做同样的事情? ?想要的结果是这样的:[
{
"_id": "58a4fa0e24180825b05e14e9",
"user_id": "589cf6511b94281f34617a13",
"user": {
"firstname": "John",
"lastname": "Doe"
},
"stages": [
{
"user_id": "589cf6511b94281f34617a13",
"firstname": "John",
"lastname": "Doe"
},
{
"user_id": "589cf6511b94281f346343c3"
"firstname": "Jane",
"lastname": "Doe"
}
],
}
]
最佳答案
我相信你缺少的是在舞台上的放松和之后的群聊。我测试了以下代码并得到了类似的结果:
db.collection('things').aggregate([
{ $match: finder },
{ $lookup: { from: 'users',
localField: 'user_id',
foreignField: '_id',
as: 'user'
}
},
{ $unwind: '$stages' },
{$lookup : {from : 'users', localField: 'stages.user_id', foreignField: '_id', as : 'stages'}},
{$group : { _id: '$_id', userId: "$userId",..., stages: {$push : "$stages"}}}
]);
希望我的代码有用
关于MongoDB:如何在数组中查找字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42263299/