问题描述
我正在使用MongoDB Shell版本3.6.3。 我有两个集合1.用户2.业务 我在下面给出了示例数据。
user
********
_id : 1
username : "joyjeba2"
mobile_number : 9840347197,profile_url :"http://localhost:3001/user/1599214209351_dp1.jpg"
saved_products :[1,2]
Business
*****
_id:1
name : "businessname1"
location :"location",contact_number:123456,Products : [
{ "name": "product","tags": [
"shoes","slippers"
],"description": "its a simple description","lower_price": 20,"higher_price": 30,"min_order": 20,"units": "count","media_urls": [
"http://localhost:3001/product/1586703106075_DP1.jpg"
],"_id": 1
}
{ "name": "product","_id": 2
},]
现在,我想从用户集合中的saved_products
到业务集合中的产品进行联接。
预期结果是:
_id : 1
username : "joyjeba2"
mobile_number : 9840347197,profile_url :"http://localhost:3001/user/1599214209351_dp1.jpg"
saved_product : [
{ "name": "product","_id": 1
"_business_id":1,"business_name" : "businessname1"
"location" :"location"
}
{ "name": "product","_id": 2,"_business_id":1,"business_name" : "businessname1"
"location" :"location"
},],
当产品是单独的收藏品时(在查找和展开帮助下),我可以执行此操作。但是这里的产品作为嵌套文档位于业务集合中。我怎样才能做到这一点。请帮帮我。
解决方法
您可以尝试
-
$lookup
使用管道,将saved_products
传入let -
$unwind
解构Products
数组 -
$match
产品ID -
$mergeObjects
合并业务领域和产品领域 -
$replaceRoot
替换根目录中的合并对象
db.user.aggregate([
{
$lookup: {
from: "business",let: { saved_products: "$saved_products" },pipeline: [
{ $unwind: "$Products" },{ $match: { $expr: { $in: ["$Products._id","$$saved_products"] } } },{
$replaceRoot: {
newRoot: {
$mergeObjects: [
"$Products",{
_business_id: "$_id",business_name: "$name",location: "$location"
}
]
}
}
}
],as: "saved_products"
}
}
])