我在 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'
}
})
https://stackoverflow.com/questions/4621300/