使用 Mongo 数据库如何获取不同 collection 中所有相关字段的总和

Using Mongo DB how do I get the sum of all related fields in a different collection

我有两个 collection。一个 collection 存储用户数据,另一个 collection 存储交易数据。交易数据使用用户 ID 上的外部字段引用用户数据。

我如何通过一个附加字段获取所有用户数据,该字段是金额字段上所有关联交易的总和?

用户模型由 id 和各种其他字段组成,例如

{
  id: unique_mongo_id
  name: Tom
  ...
}

交易 table 由两个主要字段组成,即对用户 ID 和交易价值的引用,例如

{
  userId: unique_mongo_user_id
  amount: 100
  ...
}

我试图实现的输出是简单获取所有用户字段和一个附加字段,该字段是所有交易数据的总和。

非常感谢您对此的帮助!

您可以使用此聚合查询:

  • 首先 $lookup 加入集合并在名为 transactions 的字段中获取值。
  • 然后用$project得到结果中字段amount$sum(即total)joined。
db.user.aggregate([
  {
    "$lookup": {
      "from": "transactions",
      "localField": "_id",
      "foreignField": "userId",
      "as": "transactions"
    }
  },
  {
    "$project": {
      "name": 1,
      "total": {
        "$sum": "$transactions.amount"
      }
    }
  }
])

示例here

collection.CountDocuments()

collection 是您的 collection 的名字。例如,如果您的 collection 名称是示例 - example.CountDocuments()