所以我的数据库中有这样的东西:
{ "_id" : ObjectId("561c2ca2153678d113d03077"), "title" : "Level 8", "rewardCoins" : NumberLong(25)}
{ "_id" : ObjectId("5615980b153678d113d02d61"), "title" : "Level 9", "rewardCoins" : NumberLong(40)}
{ "_id" : ObjectId("56159796153678d113d02d60"), "title" : "Level 10", "rewardCoins" : NumberLong(55)}
{ "_id" : ObjectId("5613f5ad153678d113d01f4a"), "title" : "Level 11", "rewardCoins" : NumberLong(70)}
所以我想在"等级11"下得到所有奖励币的总和。 总数应为55 + 40 + 25 = 120
我想知道如何使用mongo shell获得此功能?
我正在尝试类似的事情:
db.userlevels.aggregate([
{
$match: {
"title": {$lt: "Level 11"}
},
},
{
$group: {
"_id": {"name": "Level 11"},
"totalAmount": { $sum: "$rewardCoins"}
}
}
])
但我没有得到我所期待的...... 提示或解决方案将非常感激。感谢。
答案 0 :(得分:2)
考虑将额外的数字字段引入存储级别:
{ "_id" : ObjectId("561c2ca2153678d113d03077"), "title" : "Level 8", "rewardCoins" : NumberLong(25), level: 8}
{ "_id" : ObjectId("5615980b153678d113d02d61"), "title" : "Level 9", "rewardCoins" : NumberLong(40), level: 9}
{ "_id" : ObjectId("56159796153678d113d02d60"), "title" : "Level 10", "rewardCoins" : NumberLong(55), level: 10}
{ "_id" : ObjectId("5613f5ad153678d113d01f4a"), "title" : "Level 11", "rewardCoins" : NumberLong(70), level: 11}
将它作为标题的一部分然后比较字符串有点奇怪。然后这个聚合查询应该完成这项工作:
db.userlevels.aggregate([{$match: {"level": {$lt: 11}}}, {$group: {"_id": null, "totalAmount": { $sum: "$rewardCoins"}}}])