MongoDB聚合管道的错误结果
我是Nodejs和MongoDB的新手。我想使用聚合管道从多个表获取数据。因此,我的表结构是这样的:
类别:
_id, category_name, ...
产品:
_id, product_name, category_id, ...
购买:
_id, buyer_id, product_id, price, ...
我想获得这样的所有产品列表:
预期结果:
{
_id : "1",
product_name: "abc",
category : {
category_name: "xyz"
},
purchased : {
buyer_id: "101",
price : "$10"
}
}
我的聚合管道是这样的:
[
{
"$match": {
"category_id": "627f8118a9ef34edc9be1f51"
}
},
{
"$addFields": {
"category_id": {
"$toObjectId": "$category_id"
}
}
},
{
"$lookup": {
"from": "categories",
"localField": "category_id",
"foreignField": "_id",
"as": "category"
}
},
{
"$unwind": {
"path": "$category"
}
},
{
"$lookup": {
"from": "purchases",
"let": {
"main_product_id": "$_id",
"product_buyer_id": "627f7cf5a9ef34edc9be1f41"
},
"as": "purchase",
"pipeline": [
{
"$addFields": {
"product_id": {
"$toObjectId": "$product_id"
}
}
},
{
"$match": {
"$expr": {
"$and": [
{
"$eq": [
"$product_id",
"$$main_product_id"
]
},
{
"$eq": [
"$buyer_id",
"$$product_buyer_id"
]
}
]
}
}
}
]
}
},
{
"$unwind": {
"path": "$purchase",
"preserveNullAndEmptyArrays": true
}
}
]
如果我在Mongo-compass Softwere中运行此管道,则会是预期结果。但是,当我在nodejs代码中运行同一管道时,它不会在结果中返回购买
对象。
从过去的5天开始,我面临这个问题,还找不到问题。任何人都可以帮我吗?任何小的帮助都对我有很大的帮助。
谢谢。
I am new To NodeJS and MongoDB. I want to fetch data from the multiple table using aggregation pipeline. SO My table structure is like this :
Category :
_id, category_name, ...
Product :
_id, product_name, category_id, ...
purchase :
_id, buyer_id, product_id, price, ...
I want to get all product list like this :
Expected Result :
{
_id : "1",
product_name: "abc",
category : {
category_name: "xyz"
},
purchased : {
buyer_id: "101",
price : "$10"
}
}
My Aggregation pipeline is like this :
[
{
"$match": {
"category_id": "627f8118a9ef34edc9be1f51"
}
},
{
"$addFields": {
"category_id": {
"$toObjectId": "$category_id"
}
}
},
{
"$lookup": {
"from": "categories",
"localField": "category_id",
"foreignField": "_id",
"as": "category"
}
},
{
"$unwind": {
"path": "$category"
}
},
{
"$lookup": {
"from": "purchases",
"let": {
"main_product_id": "$_id",
"product_buyer_id": "627f7cf5a9ef34edc9be1f41"
},
"as": "purchase",
"pipeline": [
{
"$addFields": {
"product_id": {
"$toObjectId": "$product_id"
}
}
},
{
"$match": {
"$expr": {
"$and": [
{
"$eq": [
"$product_id",
"$main_product_id"
]
},
{
"$eq": [
"$buyer_id",
"$product_buyer_id"
]
}
]
}
}
}
]
}
},
{
"$unwind": {
"path": "$purchase",
"preserveNullAndEmptyArrays": true
}
}
]
If I run this pipeline in mongo-compass softwere then It's return expected result. But when I run this same pipeline in NodeJS Code, It does not return purchase
object in result.
I am facing this problem from last 5 days Can't find The Problem Yet. Can anyone please help me. Any kind of small help would be great help for me.
Thank You.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论