【发布时间】:2015-03-18 14:03:07
【问题描述】:
我在我的集合中使用时间戳,所以每个文档都有一个时间戳,用户希望从“ts1”(时间戳1)到“ts2”获取文档(时间戳 2),但是该间隔内的文档太多,所以我不想只返回每 n 个,例如如果有 100000 个文档,我需要显示 1000 个文档,所以 100000/1000=100。每 100 个文档。
这可能吗,我怎么能做到这一点。
PS。我需要在 Meteor 发布方法中查询这个。
这是我目前得到的:
Meteor.publish('documents-chunk', function (from, to) {
//get find documents count and get nth
var count = Documents.find({time: {$gte: from, $lte: to}}).count();
if (count > 2000) {
var nth = Math.round(count / 1000);
return Documents.find(/*query every nth*/);
}
return Documents.find({time: {$gte: from, $lte: to}});
});
解决方案:
我~用 Matt K 的回答解决了这个问题。
这就是我所做的:首先我修改了我的收藏并添加了额外的“id”字段:
**
1.
**
Document.find({}, {sort: {time: 1}}).forEach(function (c, i) {
Document.update(c, {$set: {id: i + 1}});
console.log(i + 1);
});
这个集合有不到 1,5M 的记录,所以需要一些时间,(还要注意,我必须在这个集合中添加索引 {time: 1} 否则它会导致数据库崩溃)
**
2.
**
Meteor.publish('documents-chunk', function (from, to) {
var nth = Math.round(Documents.find({time: {$gte: from, $lte: to}}, {sort: {time: 1}}).count() / 1000);
return Documents.find({time: {$gte: from, $lte: to, $mod: [nth, 0]}}, {sort: {time: 1}});
});
这对我有用,现在我得到了我需要的结果;
我在http://docs.mongodb.org/manual/tutorial/create-an-auto-incrementing-field/ 看到不推荐这种方法。但是目前我找不到任何其他解决方案,虽然我发现它是请求https://jira.mongodb.org/browse/SERVER-2397所以也许将来会有更清洁的解决方案,但现在它可以工作。
【问题讨论】: