【问题标题】:How to get data from multiple collections in mongodb using mongoose?如何使用 mongoose 从 mongodb 中的多个集合中获取数据?
【发布时间】:2022-02-01 06:22:27
【问题描述】:

我在 mongoDB 中有 3 个集合,结构如下

用户:

"name":""
"email":""
"phone":""
"city":""
"customerID":""

船舶:

"address":""
"city":""
"pincode":""
"porderID":""
"customerID":""

订单:

"productName":""
"quantity":""
"pricing":""
"mrp":""
"porderID":""
"customerID":""

如何编写一个 get 请求或聚合函数,以这样的 json 格式返回所有 customerID?

[{

customerID:"",
BuyOrder:[{
porderID:"",
productName:"",
quantity:""
ShipmentDetail:[
address:""
city:""
pincode:""
]
}],

customerID:"",
BuyOrder:[{
porderID:"",
productName:"",
quantity:""
ShipmentDetail:[
address:""
city:""
pincode:""
]
}],

}]

任何建议都会有所帮助。

【问题讨论】:

标签: javascript json mongodb mongoose aggregation-framework


【解决方案1】:

不太清楚您想要什么...没有输入/输出示例,没有有效的 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"
          }
        }
      ]
    }
  },
  
])

例如here

您还可以添加$project 阶段以仅输出您想要的字段,例如this example,结果是:

[
  {
    "BuyOrder": [
      {
        "ShipmentDetail": [
          {
            "address": "",
            "city": "",
            "pincode": ""
          }
        ],
        "porderID": "",
        "pricing": "",
        "productName": "",
        "quantity": ""
      }
    ],
    "customerID": ""
  }
]

【讨论】:

    猜你喜欢
    • 2016-06-20
    • 2012-06-04
    • 1970-01-01
    • 1970-01-01
    • 2011-11-20
    • 2019-03-20
    • 2016-06-18
    • 2018-08-21
    • 2021-04-23
    相关资源
    最近更新 更多