如何使用 mongoose 从 mongodb 中的多个集合中获取数据?
How to get data from multiple collections in mongodb using mongoose?
我在 mongoDB 中有 3 个集合,结构如下
用户:
"name":""
"email":""
"phone":""
"city":""
"customerID":""
船只:
"address":""
"city":""
"pincode":""
"porderID":""
"customerID":""
订单:
"productName":""
"quantity":""
"pricing":""
"mrp":""
"porderID":""
"customerID":""
如何编写 returns 像这样 json 中所有客户 ID 的获取请求或聚合函数?
[{
customerID:"",
BuyOrder:[{
porderID:"",
productName:"",
quantity:""
ShipmentDetail:[
address:""
city:""
pincode:""
]
}],
customerID:"",
BuyOrder:[{
porderID:"",
productName:"",
quantity:""
ShipmentDetail:[
address:""
city:""
pincode:""
]
}],
}]
任何建议都会有所帮助。
不太清楚你想要什么...没有 input/output 示例,没有有效的 JSON... 并不容易,但我认为你正在寻找这样的东西:
此查询是一个嵌套的 $lookup
,其中每个用户使用 customerID
与 orders
加入集合,并且订单与 ships
使用 customerID
也是。
db.users.aggregate([
{
"$lookup": {
"from": "orders",
"localField": "customerID",
"foreignField": "customerID",
"as": "BuyOrder",
"pipeline": [
{
"$lookup": {
"from": "ships",
"localField": "customerID",
"foreignField": "customerID",
"as": "ShipmentDetail"
}
}
]
}
},
])
示例here
您还可以添加一个 $project
阶段以仅输出您想要的字段,例如 this example 结果为:
[
{
"BuyOrder": [
{
"ShipmentDetail": [
{
"address": "",
"city": "",
"pincode": ""
}
],
"porderID": "",
"pricing": "",
"productName": "",
"quantity": ""
}
],
"customerID": ""
}
]
我在 mongoDB 中有 3 个集合,结构如下
用户:
"name":""
"email":""
"phone":""
"city":""
"customerID":""
船只:
"address":""
"city":""
"pincode":""
"porderID":""
"customerID":""
订单:
"productName":""
"quantity":""
"pricing":""
"mrp":""
"porderID":""
"customerID":""
如何编写 returns 像这样 json 中所有客户 ID 的获取请求或聚合函数?
[{
customerID:"",
BuyOrder:[{
porderID:"",
productName:"",
quantity:""
ShipmentDetail:[
address:""
city:""
pincode:""
]
}],
customerID:"",
BuyOrder:[{
porderID:"",
productName:"",
quantity:""
ShipmentDetail:[
address:""
city:""
pincode:""
]
}],
}]
任何建议都会有所帮助。
不太清楚你想要什么...没有 input/output 示例,没有有效的 JSON... 并不容易,但我认为你正在寻找这样的东西:
此查询是一个嵌套的 $lookup
,其中每个用户使用 customerID
与 orders
加入集合,并且订单与 ships
使用 customerID
也是。
db.users.aggregate([
{
"$lookup": {
"from": "orders",
"localField": "customerID",
"foreignField": "customerID",
"as": "BuyOrder",
"pipeline": [
{
"$lookup": {
"from": "ships",
"localField": "customerID",
"foreignField": "customerID",
"as": "ShipmentDetail"
}
}
]
}
},
])
示例here
您还可以添加一个 $project
阶段以仅输出您想要的字段,例如 this example 结果为:
[
{
"BuyOrder": [
{
"ShipmentDetail": [
{
"address": "",
"city": "",
"pincode": ""
}
],
"porderID": "",
"pricing": "",
"productName": "",
"quantity": ""
}
],
"customerID": ""
}
]