[英]How to join two collection in mongodb similar like inner join in mysql
首次收藏: 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"
}}
]);
但是上面的查詢不起作用:(
這對我有用
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",
},
}]
}}
])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.