英文:
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
}
}
])
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论