我有这样的数据集:
{
"_id" : ObjectId("5a4c6fb6993a721b3479a27e"),
"score" : 8.3,
"page" : "message",
"lastmodified" : ISODate("2018-01-03T06:49:19.232Z"),
"createdate" : ISODate("2018-01-03T05:52:54.446Z"),
"slug" : [
"@APPLE"
],
"__v" : 0
},
{
"_id" : ObjectId("5a4c6fb6993a721b3479a27e"),
"score" : 9.3,
"page" : "@BANANA",
"lastmodified" : ISODate("2018-01-03T06:49:19.232Z"),
"createdate" : ISODate("2018-01-03T05:52:54.446Z"),
"slug" : [
"@APPLE"
],
"__v" : 0
}
{
"_id" : ObjectId("5a4c6fb6993a721b3479a27e"),
"score" : 5.3,
"page" : "@BANANA",
"lastmodified" : ISODate("2018-01-03T06:49:19.232Z"),
"createdate" : ISODate("2018-01-03T05:52:54.446Z"),
"slug" : [
"@BANANA"
],
"__v" : 0
}
现在我想根据我的过滤器计算得分总和:
@APPLE: 8.3+9.3 = 17.6 i.e @APPLE: 17.6,
@BANANA: 9.3+5.3 = 14.6 i.e @BANANA: 14.6
因此,我必须只选择最近1小时的数据而不是选择整个数据库 。所以我的查询是这样的
var newTime = new Date();
newTime.setHours( newTime.getHours() - 1 );
db.Test.find({"lastmodified":{$gt: newTime}})
所以通过这个我只能获得最后1小时的价值。现在我很困惑,我怎么能用过滤器来做总结。我还附上了过滤查询,即
db.Test.find({"lastmodified":{$gt: newTime}}, {$or: [{slug: {$in: ['@APPLE']}}, {page: '@APPLE'}]})
但它没有给出任何东西。任何帮助表示赞赏
答案 0 :(得分:0)
尝试此聚合查询...
db.tests.aggregate([{
"$unwind": "$slug"
},
{
"$group": {
"_id": "$slug",
"totalScore": {
"$sum": "$score"
}
}
}
]);
结果:
{
"_id" : "@BANANA",
"totalScore" : 5.3
}
{
"_id" : "@APPLE",
"totalScore" : 17.6
}