Node.js 如何为数组mongodb聚合执行多个$lookup
如何对数组执行聚合(mongodb)中的Node.js 如何为数组mongodb聚合执行多个$lookup,node.js,mongodb,mongoose,aggregation-framework,Node.js,Mongodb,Mongoose,Aggregation Framework,如何对数组执行聚合(mongodb)中的$lookup { messages: [{ "_id" : ObjectId("5bfc43f2bbc4176ecc1c5f83"), "text" : "text1", "sender" : { "id" : &q
$lookup
{
messages: [{
"_id" : ObjectId("5bfc43f2bbc4176ecc1c5f83"),
"text" : "text1",
"sender" : {
"id" : "36046fc2e70dd508a0bf1f36fd2daa20"
}
}, {
"_id" : ObjectId("5bfc43f2bbc4176ecc1c5f83"),
"text" : "text2",
"sender" : {
"id" : "36046fc2e70dd508a0bf1f36fd2daa22"
}
}],
"filed1": { ... },
"filed2": { ... }
}
如何从帐户集合中对发件人id执行$lookup
尝试:
您可以使用下面的聚合
db.collection.aggregate([
{ "$unwind": "$messages" },
{ "$lookup": {
"from": "accounts",
"localField": "messages.sender.id",
"foreignField": "id",
"as": "messages.sender.user"
}},
{ "$unwind": "$messages.sender.user" }
{ "$group": {
"_id": "$_id",
"messages": { "$push": "$messages" },
"filed1": { "$first": "$filed1" },
"filed2": { "$first": "$filed2" }
}}
])
答案对你有用吗?不确定你在问什么。但是如果下面的答案对你有效,那么请接受它,如果你有任何进一步的疑问,那么请在单独的线程中问一个新问题。我不能创建新线程,但它可以为什么?我一定会帮你的。在
$group
阶段将所有文档放在一个数组中不是一件好工作。它将超过16MB的限制。我已经把你现在要问的一个问题投了赞成票,我听不懂。请编辑你的问题并把全部解释放在上面。
db.collection.aggregate([
{ "$unwind": "$messages" },
{ "$lookup": {
"from": "accounts",
"localField": "messages.sender.id",
"foreignField": "id",
"as": "messages.sender.user"
}},
{ "$unwind": "$messages.sender.user" }
{ "$group": {
"_id": "$_id",
"messages": { "$push": "$messages" },
"filed1": { "$first": "$filed1" },
"filed2": { "$first": "$filed2" }
}}
])