mongodb - 如何对 MongoDB 集合中所有文档的键值求和

我在 MongoDB 中有收藏:

{ "_id" : ObjectId("4d2407265ff08824e3000001"), "subida" : 3.95 }
{ "_id" : ObjectId("4d2551b4ae9fa739640df821"), "subida" : 6.03 }
{ "_id" : ObjectId("4d255b115ff08821c2000001"), "subida" : 5.53 }
{ "_id" : ObjectId("4d25e8d55ff08814f8000001"), "subida" : 1.96 }

如何对所有文档中的键值求和,例如 "subida"?有了上述文件,我应该会收到以下内容:

{ "subida" : 17.47 }

最佳答案

在这种情况下,聚合比 mapReduce 更简单、更高效:

db.collection.aggregate({
    $group: {
        _id: '',
        subida: { $sum: '$subida' }
    }
 }, {
    $project: {
        _id: 0,
        subida: '$subida'
    }
})
  1. 使用 $group 和 $sum 来计算总和
  2. 使用投影的 $project 运算符删除 $group 运算符所需的 id 键

https://stackoverflow.com/questions/4621300/

相关文章:

mongodb - 查询 MongoDB 中的内部数组大小

mongodb - 将 mongodb 数据库从本地主机迁移到远程服务器

mongodb - 在 MongoDb 中按 15 分钟的时间间隔对结果进行分组

javascript - Mongoose 查找/更新子文档

c# - 如何通过 .NET 在 MongoDB 中创建索引

mongodb - 使用 Mongoid 批量插入/更新?

mongodb - 数据库中的集合数量限制

mongodb - 如何修复我的mongodb?

python - mongodb游标id无效错误

python - 在日期时间的月、日、年...上查询 Mongodb