第一次收集:transactions
{
"_id": "QH2yYgJyE8A1zKBAWTv_T0VmvceS5l7p15Lki_i2PwfGoV3kHzkeqa6yFFm5oLhwriF39bAl2b4wgSIkvwy-MA",
"rate": [
{
"user_id": ObjectId("58aeb5bd21b8ae596d3c9869"),
"rate": "4",
"option": "QUICK_BITE",
"message": "Good"
}
]
}
第二次收集:users
{
"_id": ObjectId("58aeb5bd21b8ae596d3c9869"),
"username": "ravi",
"profile": {
"firstname": "Ravi",
"lastname": "Kumar",
"email": "ravi@gamil.com",
"phone_no": "",
"company_name": "gmail",
"image": ""
}
},
{
"_id": ObjectId("58c104da21b8aeac733c9869"),
"username": "",
"profile": {
"firstname": "lalit",
"lastname": "sharma",
"email": "lxyz@gmail.com",
"phone_no": "",
"company_name": ""
}
},
{
"_id": ObjectId("58c12afc21b8aef8553c9869"),
"username": "",
"profile": {
"firstname": "Aijaz",
"lastname": "Haidar",
"email": "jazhaidar@gmail.com",
"phone_no": "",
"company_name": "yahoo",
"image": ""
}
}
我想加入users
集合与transactions
集合,以便我可以在费率公平中获取用户完整的个人资料详情。
输出类似
的内容 {
"_id" : ObjectId("58c1200321b8ae2d413c98a5"),
"rate" : [
{
"rate" : "4",
"option" : "QUICK_BITE",
"message" : "Good",
"profile" : {
"firstname" : "Ravi",
"lastname" : "Kumar",
"email" : "ravi@gamil.com",
"phone_no" : "",
"company_name" : "gmail",
"image" : ""
}
}
]
}
现在我以下列方式使用$lookup
合并两个集合:
db.transactions.aggregate([
{$lookup: {
from: "users",
localField: "rate.user_id",
foreignField: "_id",
as: "profile"
}}
]);
但上面的查询无效:(
答案 0 :(得分:0)
这对我有用
db.transactions.aggregate([
{
$match: { "name": "The Mean Fiddler" }
},
{
$unwind: "$rate"
},
{
$lookup:
{
from: "users",
localField: "rate.user_id",
foreignField: "_id",
as: "userInfo"
}
},{$unwind:"$userInfo"},{$unwind:"$userInfo.profile"},
{$project:{
"_id":1,
"rate":[{
'rate':"$rate.rate",
'option':"$rate.option",
'message':"$rate.message",
'profile' : {
'firstname' : "$userInfo.profile.firstname",
'lastname' :"$userInfo.profile.lastname" ,
'email' : "$userInfo.profile.email",
'phone_no' : "$userInfo.profile.phone_no",
'company_name' : "$userInfo.profile.company_name",
'image' : "$userInfo.profile.image",
},
}]
}}
])