Mongo DB 左连接具有一对多关系

问题描述 投票:0回答:1

我需要有关此 Mongo DB 代码的帮助。

我有两个表(集合),分别是

orders
users
。我的
orders
表有一个名为 userId 的引用字段,该字段引用下订单的用户。一个用户可以有多个订单。我的
orders
表有这些字段:(_id、userId、products[]、amount)和其他一些字段,而我的
users
表有这些字段(_id、name、username)和一些其他字段。

我想连接两个表并检索

users
集合中的所有字段,以及
orders
表中属于每个用户的总金额之和。

这是我的代码:

const data = await Order.aggregate([ { $group: { _id: '$userId', totalAmount: {$sum : '$amount'} }, }, { $lookup: { from: 'users', localField: 'userId', foreignField: '_id', as: 'user_orders', }, }, { $unwind: { path: '$user_orders', preserveNullAndEmptyArrays: true, }, }, { $project: { _id: 1, totalAmount: 1, }, }, ]);

我的期待:

[ { _id: id, name: name, username: username, totalAmount: sum of the amout field in 
订单
table that has the document "_id" }, { _id: id, name: name, username: username, totalAmount: sum of the amout field in
订单
 table that has the document "_id" }, ... ]

我得到的结果:

[ { "_id": "6582e50ca32d27e9638797aa", "totalAmount": 840 }, { "_id": "65805c533b1ce2ec300cd31f", "totalAmount": 2520 }, { "_id": "63f88bea05cc08d340effa59", "totalAmount": 840 }, { "_id": "6582e28e8ee96b5d6962b269", "totalAmount": 840 } ]

database mongodb mongoose mongodb-query
1个回答
0
投票

您可以使用此聚合:

const data = await Order.aggregate([
  {
    $group: {
      "_id": "$userId",
      "totalAmount": {
        $sum: "$amount"
      }
    }
  },
  {
    $lookup: {
      "from": "users",
      "localField": "_id",
      "foreignField": "_id",
      "as": "user"
    }
  },
  {
    $unwind: "$user"
  },
  {
    $project: {
      "name": "$user.name",
      "username": "$user.username",
      "totalAmount": 1
    }
  }
])

请参阅此处了解工作示例。

© www.soinside.com 2019 - 2024. All rights reserved.