Node.js 如何在NodeJS的MongoDB驱动程序中加入嵌套数组?
我使用的是MongoDB外壳版本v3.6.3。 我有两个收藏。用户2。生意 我在下面给出了示例数据Node.js 如何在NodeJS的MongoDB驱动程序中加入嵌套数组?,node.js,mongodb,mongodb-nodejs-driver,Node.js,Mongodb,Mongodb Nodejs Driver,我使用的是MongoDB外壳版本v3.6.3。 我有两个收藏。用户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
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",
"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": 2
},
]
现在,我想将用户集合中的saved_products
连接到业务集合中的products
预期结果是:
_id : 1
username : "joyjeba2"
mobile_number : 9840347197,
profile_url :"http://localhost:3001/user/1599214209351_dp1.jpg"
saved_product : [
{ "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
"_business_id":1,
"business_name" : "businessname1"
"location" :"location"
}
{ "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": 2,
"_business_id":1,
"business_name" : "businessname1"
"location" :"location"
},
],
我能够做到这一点时,产品是单独收集(与查找和放松的帮助)。但在这里,产品作为嵌套文档存在于业务集合中。我怎样才能做到这一点。请帮帮我。你可以试试
使用管道,在let中传递$lookup
已保存的\u产品
解构$unwind
阵列产品
产品id$match
合并业务字段和产品字段$mergeObjects
替换根目录中的合并对象$replaceRoot
谢谢。它在turivishal起作用。由于我的版本是3.6.3,我需要用replaceRoot更改replaceWith。
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"
}
}
])