Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/mongodb/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
获取mongodb中某条记录之前的所有记录的总和_Mongodb_Mongodb Query_Aggregation Framework - Fatal编程技术网

获取mongodb中某条记录之前的所有记录的总和

获取mongodb中某条记录之前的所有记录的总和,mongodb,mongodb-query,aggregation-framework,Mongodb,Mongodb Query,Aggregation Framework,我的数据库中有这样的东西: { "_id" : ObjectId("561c2ca2153678d113d03077"), "title" : "Level 8", "rewardCoins" : NumberLong(25)} { "_id" : ObjectId("5615980b153678d113d02d61"), "title" : "Level 9", "rewardCoins" : NumberLong(40)} { "_id" : ObjectId("56159796153678

我的数据库中有这样的东西:

{ "_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"}
        }
    }
])
但我没有得到我所期待的。。。
如有任何提示或解决方案,将不胜感激。谢谢。

考虑引入额外的数字字段来存储级别:

{ "_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"}}}])

使用字符串比较无法获得准确的结果。如果您可以将级别存储在数字字段中,那么您的筛选查询将在上述模式下工作,则
$match
管道将只将
“级别10”
的文档输送到下一个管道,因为比较字符串逻辑
(“级别9”<“级别10”)
是错误的。如果我将它与对象id(_id)@chridman匹配,这能起作用吗?