我在项目中使用mongoDb,在对嵌入式数据进行查找时遇到问题..我搜索了问题并读取了类似的代码..但它们对我的问题没有帮助。
我的意思是我的嵌入文档中有一个名为user
的变量,我想通过查找来加载其数据。
这是我的文档的样子:
"_id" : ObjectId("5d0f6a993702da22bc00474d"),
"quotes" : [
{
"amount" : NumberInt(100),
"user" : {
"_id" : ObjectId("5cc69f7f46ab4cedda5c3c12")
},
"details" : "some quote details",
"_id" : ObjectId("5d0f6a993702da22bc00474c"),
"status" : "a"
},
{
"amount" : NumberInt(120),
"user" : {
"_id" : ObjectId("5cc69kij46ab4cedda5c3c12")
},
"details" : "some quote details 2",
"_id" : ObjectId("5d0f6a993702da22bc00484k"),
"status" : "a"
}
],
"status" : "Approved",
"title" : "gardening",
"created_at" : NumberInt(1560841417)
所以我希望我的输出是这样的:
"_id" : ObjectId("5d0f6a993702da22bc00474d"),
"quotes" : [
{
"amount" : NumberInt(100),
"user" : {
"_id" : ObjectId("5cc69f7f46ab4cedda5c3c12"),
"firstName": "John",
"lastNAme": "Doe",
"phone": 514298742
},
"details" : "some quote details",
"_id" : ObjectId("5d0f6a993702da22bc00474c"),
"status" : "a"
},
{
"amount" : NumberInt(120),
"user" : {
"_id" : ObjectId("5cc69kij46ab4cedda5c3c12")
"firstName": "Jane",
"lastNAme": "Doe",
"phone": 5148547642
},
"details" : "some quote details 2",
"_id" : ObjectId("5d0f6a993702da22bc00484k"),
"status" : "a"
}
],
"status" : "Approved",
"title" : "gardening",
"created_at" : NumberInt(1560841417)
答案 0 :(得分:0)
我找到了解决方案..这对我有用。
.aggregate([
{
{
"$unwind": {
"path": "$quotes",
"preserveNullAndEmptyArrays": true
}
},
{
"$lookup": {
"from": "users",
"localField": "quotes.user._id",
"foreignField": "_id",
"as": "quotes.user",
}
},
{
"$unwind": {
"path": "$quotes.user",
"preserveNullAndEmptyArrays": true
}
},
{
"$group": {
"_id": null,
"quotes": {"$push": "$quotes"},
"status": {"$first": "$status"},
"title": {"$first": "$title"},
"created_at": {"$first": "$created_at"},
}
},
}
])
如果有人遇到同样的问题,我会发布答案。