[英]How to get data from multiple collections in mongodb using mongoose?
我在 mongoDB 中有 3 个 collections 具有以下结构
用户:
"name":""
"email":""
"phone":""
"city":""
"customerID":""
船舶:
"address":""
"city":""
"pincode":""
"porderID":""
"customerID":""
订单:
"productName":""
"quantity":""
"pricing":""
"mrp":""
"porderID":""
"customerID":""
我如何编写一个 get 请求或聚合 function 来返回 json 中的所有 customerID 像这样?
[{
customerID:"",
BuyOrder:[{
porderID:"",
productName:"",
quantity:""
ShipmentDetail:[
address:""
city:""
pincode:""
]
}],
customerID:"",
BuyOrder:[{
porderID:"",
productName:"",
quantity:""
ShipmentDetail:[
address:""
city:""
pincode:""
]
}],
}]
任何的意见都将会有帮助。
不太清楚你想要什么......没有输入/输出示例,没有有效的 JSON...... 并不容易,但我认为你正在寻找这样的东西:
该查询是一个嵌套的$lookup
,其中每个用户使用customerID
将订单与orders
连接起来,并且订单也使用customerID
与ships
连接。
db.users.aggregate([
{
"$lookup": {
"from": "orders",
"localField": "customerID",
"foreignField": "customerID",
"as": "BuyOrder",
"pipeline": [
{
"$lookup": {
"from": "ships",
"localField": "customerID",
"foreignField": "customerID",
"as": "ShipmentDetail"
}
}
]
}
},
])
这里的例子
您还可以将$project
阶段添加到 output 仅您想要的字段,例如结果为:
[
{
"BuyOrder": [
{
"ShipmentDetail": [
{
"address": "",
"city": "",
"pincode": ""
}
],
"porderID": "",
"pricing": "",
"productName": "",
"quantity": ""
}
],
"customerID": ""
}
]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.