MongoDb $ lookup查询具有对象数组中的多个字段 [英] MongoDb $lookup query with multiple fields from objects array
问题描述
此问题先前已被标记为 该问题 我可以肯定地确认它不是。
This question has previously been marked as a duplicate of this question I can with certainty confirm that it is not.
这不是链接问题的重复,因为所讨论的元素不是数组而是作为字段嵌入到数组的各个对象中。我完全知道链接问题中的查询应该如何工作,但是这种情况与我的情况不同。
This is not a duplicate of the linked question because the elements in question are not an array but embedded in individual objects of an array as fields. I am fully aware of how the query in the linked question should work, however that scenario is different from mine.
我对有疑问$ lookup
查询MongoDb。我的数据结构如下:
I have a question regarding the $lookup
query of MongoDb. My data structure looks as follows:
我的事件 集合包含以下单个文档:
My "Event" collection contains this single document:
{
"_id": ObjectId("mongodbobjectid..."),
"name": "Some Event",
"attendees": [
{
"type": 1,
"status": 2,
"contact": ObjectId("mongodbobjectidHEX1")
},
{
"type": 7,
"status": 4,
"contact": ObjectId("mongodbobjectidHEX2")
}
]
}
我的联系人 集合包含以下文档:
My "Contact" collection contains these documents:
{
"_id": ObjectId("mongodbobjectidHEX1"),
"name": "John Doe",
"age": 35
},
{
"_id": ObjectId("mongodbobjectidHEX2"),
"name": "Peter Pan",
"age": 60
}
我想做的是总计
qu在事件 集合上使用 $ lookup
运算符进行操作,并获得带有完整联系人数据的以下结果:
What I want to do is perform an aggregate
query with the $lookup
operator on the "Event" collection and get the following result with full "contact" data:
{
"_id": ObjectId("mongodbobjectid..."),
"name": "Some Event",
"attendees": [
{
"type": 1,
"status": 2,
"contact": {
"_id": ObjectId("mongodbobjectidHEX1"),
"name": "John Doe",
"age": 35
}
},
{
"type": 7,
"status": 4,
"contact": {
"_id": ObjectId("mongodbobjectidHEX2"),
"name": "Peter Pan",
"age": 60
}
}
]
}
我对另一个文档中引用的联系人的单个元素执行了相同的操作,但是从未嵌入到数组中。我不确定要传递哪个管道参数来获得上面显示的结果?
I have done the same with single elements of "Contact" referenced in another document but never when embedded in an array. I am unsure of which pipeline arguments to pass to get the above shown result?
我还想添加一个 $ match
查询管道以过滤数据,但这并不是我真正的问题。
I also want to add a $match
query to the pipeline to filter the data, but that is not really part of my question.
推荐答案
试试这个
db.getCollection('Event').aggregate([{ "$unwind": "$attendees" },
{ "$lookup" : { "from" : "Contact", "localField" : "attendees.contact", "foreignField": "_id", "as" : "contactlist" } },
{ "$unwind": "$contactlist" },
{ "$project" :{
"attendees.type" : 1,
"attendees.status" : 1,
"attendees.contact" : "$contactlist",
"name": 1, "_id": 1
}
},
{
"$group" : {
_id : "$_id" ,
"name" : { $first : "$name" },
"attendees" : { $push : "$attendees" }
}
}
])
这篇关于MongoDb $ lookup查询具有对象数组中的多个字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!