[英]How to merge result from $lookup with subdocuments
Consider the following toy example:考虑以下玩具示例:
Collection shops
收藏shops
{
"products": [
{ id: "abc", price: 20.5 },
{ id: "abd", price: 34.0 }
]
}
Collection products
收藏products
{
_id: "abc",
name: "Apple"
}
Running the following query...运行以下查询...
db.shops.aggregate([
{
$lookup: {
from: "products",
localField: "products.id",
foreignField: "_id",
as: "product_info"
}
}
])
returns...返回...
[{
"products": [
{ id: "abc", price: 20.5 },
{ id: "abd", price: 34.0 }
],
"product_info": [
{ _id: "abc", name: "Apple" },
{ _id: "abd", name: "Orange" }
]
}]
Is there a way to "merge" products
and product_info
to get the following?有没有办法“合并” products
和product_info
以获得以下信息?
[{
"products": [
{ id: "abc", price: 20.5, name: "Apple" },
{ id: "abd", price: 34.0, name: "Orange" }
],
}]
Thanks for your help!谢谢你的帮助!
You can use below aggregation您可以使用以下聚合
db.shops.aggregate([
{ $unwind: "$products" },
{
$lookup: {
from: "products",
localField: "products.id",
foreignField: "_id",
as: "products.name"
}
},
{ $unwind: "$products.name" },
{ $addFields: { "products.name": "$products.name.name" }},
{ $group: {
_id: "$_id",
products: {
$push: "$products"
}
}}
])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.