Mongodb 在嵌入文档数组中查找引用文档
我有两套。 其中一个包含一个对象数组。这些对象拥有另一个集合中文档id为的字段。 目标是用文档“替换”ref。听起来很简单,但我不知道如何存档 例如 收藏“产品” 收集“订单” 我需要查询的是:Mongodb 在嵌入文档数组中查找引用文档,mongodb,aggregation-framework,lookup,Mongodb,Aggregation Framework,Lookup,我有两套。 其中一个包含一个对象数组。这些对象拥有另一个集合中文档id为的字段。 目标是用文档“替换”ref。听起来很简单,但我不知道如何存档 例如 收藏“产品” 收集“订单” 我需要查询的是: { "_id": 5765, "cart": [ { "product": { "_id": 1, "alias": "ProductA" }, "qty": 7 }, { "product": {
{ "_id": 5765,
"cart": [
{
"product": {
"_id": 1,
"alias": "ProductA"
},
"qty": 7
}, {
"product": {
"_id": 2,
"alias": "ProductC"
},
"qty": 6
}
]
}
我尝试了一个简单的查找,但是数组将只包含产品。我需要改变什么
{
$lookup: {
from: "products",
let: {
tmp: "$cart.product"
},
pipeline: [
{
$match: {
$expr: {
$in: ["$_id", "$$tmp"]
}
}
}
],
as: "cart.product"
}
}
感谢您的帮助。我添加了一个新的
$addFields
阶段来转换$lookup
阶段的输出-它获得所需的输出:
db.order.aggregate([
{
$lookup: {
from: "product",
let: {
tmp: "$cart.product"
},
pipeline: [
{
$match: {
$expr: {
$in: ["$_id", "$$tmp"]
}
}
}
],
as: "products"
}
},
{
$addFields: {
cart: {
$map: {
input: "$cart", as: "ct",
in: {
product: {
$arrayElemAt: [
{ $filter: {
input: "$products", as: "pr",
cond: {
$eq: [ "$$ct.product", "$$pr._id" ]
}
}
}, 0 ]
},
qty: "$$ct.qty"
}
}
}
}
}
] ).pretty()
哼有一个小“错误”。“购物车”中的“产品”是一个包含一个元素的数组。我怎么才能解开这个?!是的,你是对的;我没有注意到。我修复了它并更新了代码。无需展开,因为数组中只有一个元素—只需获取第一个元素即可。
{
$lookup: {
from: "products",
let: {
tmp: "$cart.product"
},
pipeline: [
{
$match: {
$expr: {
$in: ["$_id", "$$tmp"]
}
}
}
],
as: "cart.product"
}
}
db.order.aggregate([
{
$lookup: {
from: "product",
let: {
tmp: "$cart.product"
},
pipeline: [
{
$match: {
$expr: {
$in: ["$_id", "$$tmp"]
}
}
}
],
as: "products"
}
},
{
$addFields: {
cart: {
$map: {
input: "$cart", as: "ct",
in: {
product: {
$arrayElemAt: [
{ $filter: {
input: "$products", as: "pr",
cond: {
$eq: [ "$$ct.product", "$$pr._id" ]
}
}
}, 0 ]
},
qty: "$$ct.qty"
}
}
}
}
}
] ).pretty()