【发布时间】:2017-11-11 12:36:46
【问题描述】:
我正在尝试使用 Mongodb 中的查找聚合来模拟 Mongodb 中的联接并返回关系值。但它只返回当前集合的值,而不是与其相关的集合。
我有 2 个名为 wish_list 和 products 的相关集合。 wish_list 包含已标记为愿望清单的产品,它包含产品集合中的 product_id。
wish_list的文档是这样的:
"_id"
"product_id"
"user_id"
"created_at"
如您所见,product_id 存在于此集合中,即来自products 集合的id。
问题是当我尝试从wish_list 查询数据时,我想要products 集合中该产品的相关数据。它只返回来自wish_list 集合的数据(产品集合的结果是空数组)。
这是我执行的查询:
db.wish_list.aggregate([
{$match: {
user_id: "crawler"}
},
{$lookup: {
from: "wish_list",
localField: "product_id",
foreignField: "id",
as: "products"}
}
])
结果是这样的:
{
"_id" : ObjectId("5a03024551195204432afcb6"),
"product_id" : "com.thundanapps.thundpusthakam",
"user_id" : "crawler",
"created_at" : 1510146629,
"products" : []
}
/* 2 */
{
"_id" : ObjectId("5a0302565119520442375786"),
"product_id" : "com.jott.android.jottmessenger",
"user_id" : "crawler",
"created_at" : 1510146646,
"products" : []
}
P.S:我很确定 products 集合中存在等效数据。
P.S:反之亦然(从products 集合查询到with_list)时存在同样的问题。
【问题讨论】:
标签: mongodb mongodb-query aggregation-framework