使用MongoDB求多个字段的和

huangapple go评论84阅读模式
英文:

Sum multiple fields with mongo db

问题

我是新手使用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}

非常感谢。

英文:

I am new to mongodb, I have a collection of people and some of them have values that I am interested in.
I would like to sum those values and get the number of people who had them.

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

I would like to get

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

Thank you very much

答案1

得分: 1

你可以在MongoDB中使用聚合函数

db.collection.aggregate([
  {
    $match: {
      tot: { $exists: true } // 仅匹配具有"tot"字段的文档
    }
  },
  {
    $group: {
      _id: null,
      num: { $sum: 1 }, // 统计组中的文档数量
      tot: { $sum: "$tot" }, // 对组中每个文档的"tot"字段求和
      duration: { $sum: "$duration" } // 对组中每个文档的"duration"字段求和
    }
  },
  {
    $project: {
      _id: 0 // 从输出中排除"_id"字段
    }
  }
])
英文:

You can use aggregate function in 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
    }
  }
])

huangapple
  • 本文由 发表于 2023年3月7日 16:21:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/75659492.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定