mongodb 使用mongo db对多个字段求和

brccelvz  于 2023-03-07  发布在  Go
关注(0)|答案(1)|浏览(196)

我是mongodb的新手,我有一个人的集合,其中一些人有我感兴趣的值。我想把这些值相加,得到有这些值的人的数量。

{ "_id" : 001, "tot" : 10, "duration", 100}
{ "_id" : 002, "tot" : 20, "duration", 200}
{ "_id" : 003, "tot" : 20, "duration", 300}
{ "_id" : 004}
{ "_id" : 005}

我想买

{ "num" : 3, "tot" : 50, "duration" : 600}

非常感谢

ej83mcc0

ej83mcc01#

可以在mongoDB中使用聚合函数

db.collection.aggregate([
  {
    $match: {
      tot: { $exists: true } // only match documents that have a "tot" field
    }
  },
  {
    $group: {
      _id: null,
      num: { $sum: 1 }, // count the number of documents in the group
      tot: { $sum: "$tot" }, // sum the "tot" field for each document in the group
      duration: { $sum: "$duration" } // sum the "duration" field for each document in the group
    }
  },
  {
    $project: {
      _id: 0 // exclude the _id field from the output
    }
  }
])

相关问题