【发布时间】:2017-03-20 17:26:39
【问题描述】:
第一次收藏: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([ {$unwind:"$rate"}, {$lookup: { from: "users", localField: "rate.user_id", foreignField: "_id", as: "profile" }} ]);更多docs.mongodb.com/manual/reference/operator/aggregation/lookup/… -
您想要的输出有点偏离,您是不是想在
rate数组对象中嵌入profiles键? -
不,这不是强制性的,但会有 1:m 的关系,所以我希望所有用户都应该被映射
-
你说你的 $lookup 不起作用;你能edit你的问题更详细地说明它做错了什么吗?
-
@AmanMaurya 你能澄清一下这不起作用是什么意思吗?错误?出乎意料的结果?外壳存在吗?
标签: mongodb