[英]Merge arrays and group to produce a count for each combined array value
I have a dataset like this: 我有一个像这样的数据集:
{
"_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
}
Now I want to calculate the sum of score according to my Filter Like this: 现在,我想根据我的过滤器来计算分数总和,如下所示:
@APPLE: 8.3+9.3 = 17.6 i.e @APPLE: 17.6,
@BANANA: 9.3+5.3 = 14.6 i.e @BANANA: 14.6
So for this I have to pick only last 1 hour data rather than picking the whole database . 因此,为此,我只选择最后1小时的数据,而不是选择整个数据库。 So my query is like this
所以我的查询是这样的
var newTime = new Date();
newTime.setHours( newTime.getHours() - 1 );
db.Test.find({"lastmodified":{$gt: newTime}})
so By this I can get only last 1 hour value. 因此,我只能得到最近1小时的值。 Now I am confuse that how i can do sum with filter.
现在我感到困惑,我该如何用过滤器求和。 I also attached filter query ie
我还附加了过滤器查询即
db.Test.find({"lastmodified":{$gt: newTime}}, {$or: [{slug: {$in: ['@APPLE']}}, {page: '@APPLE'}]})
But it does not give anything. 但这没有任何作用。 any help is appreciated
任何帮助表示赞赏
Try this aggregate query... 试试这个汇总查询...
db.tests.aggregate([{
"$unwind": "$slug"
},
{
"$group": {
"_id": "$slug",
"totalScore": {
"$sum": "$score"
}
}
}
]);
Result: 结果:
{
"_id" : "@BANANA",
"totalScore" : 5.3
}
{
"_id" : "@APPLE",
"totalScore" : 17.6
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.