【发布时间】:2017-05-10 00:46:46
【问题描述】:
我有一个集合,其中单个文档是这样的:
{
_id: 'string'
date: Date,
user: 'usera',
sections: [
{ heading: 'string a', score: 10 },
{ heading: 'string a', score: 104 },
{ heading: 'string b', score: 123 },
{ heading: 'string b', score: 15 },
{ heading: 'string b', score: 7 },
{ heading: 'string c', score: 1 }
]
totalScore: 259
}
该集合有数十万个文档。
我需要按日期从集合中搜索,并给出部分分数的总和以及totalScores 的总和。
如果我这样做,在 Meteor 出版物中
Meteor.publish('mydata', function() {
var rets = {}
Mycollections.find({date: {$gte: new Date(2016, 8, 1), $lt: new Date (2016, 12, 24)}}.forEach(function (doc) {
if (!rets[doc.user]) {
rets[doc.user] = {
tot: 0,
sections: {}
}
}
rets[doc.user].tot += doc.totalScore;
for (var i in doc.sections) {
if (!rets[doc.user].sections[doc.sections[i].heading]) {
sections[doc.sections[i].heading] = 0;
}
rets[doc.user].sections[doc.sections[i].heading] += sections[doc.sections[i].score;
}
});
return rets;
});
Mycollections.find({date: {$gte: new Date(2016, 8, 1), $lt: new Date (2016, 12, 24)}} 的执行时间不到 0 毫秒。
对于单个 forEach 循环,执行大约需要 0-1 毫秒,如果我获取 20 000 个文档,则需要 20 秒才能发布。
MongoDB 聚合在这方面有何帮助? 或者我如何在服务器端更快地执行计算?
我需要的是集合中每个用户的总分和每个部分的总分。
{
usera: {
tot: 235
sections[
{'string a': 200},
{'string b': 35},
{...}
]
},
userb: {
...
}
}
【问题讨论】:
标签: javascript mongodb meteor mongodb-query aggregation-framework