这里一个明显的例子是使用.skip() 作为修饰符以及.limit() 以实现数据的“分页”:
collection.find({}, { "limit": 5, "skip": 5 * req.body.requestCount }, function
但如果你只是批量处理,最好过滤掉你已经看到的范围。 _id 字段为此提供了一个很好的标识符,无需其他排序。所以在第一个请求:
var lastSeen = null;
collection.find(
{},
{ "limit": 5, "sort": { "_id": 1} },
function(err,docs) {
docs.forEach(function(doc) {
// do something
lastSeen = doc._id; // keep the _id
});
}
);
下次将“lastSeen”存储在会话变量(或其他仅处理批处理的循环结构)中之后:
collection.find(
{ "_id": { "$gt": lastSeen },
{ "limit": 5, "sort": { "_id": 1} },
function(err,docs) {
docs.forEach(function(doc) {
// do something
lastSeen = doc._id; // keep the _id
});
}
);
因此排除所有结果,小于看到的最后一个 _id 值。
使用其他排序这仍然是可能的,但您需要注意最后看到的_id 和最后排序的值。自上次值更改以来,还将 _id 视为列表。
var lastSeenIds = [],
lastSeenValue = null;
collection.find(
{},
{ "limit": 5, "sort": { "other": 1, "_id": 1 } },
function(err,docs) {
docs.forEach(function(doc) {
// do something
if ( lastSeenValue != doc.other ) { // clear on change
lastSeenValue = doc.other;
lastSeenIds = [];
}
lastSeenIds.push(doc._id); // keep a list
});
}
);
然后在您的下一次迭代中使用变量:
collection.find(
{ "_id": { "$nin": lastSeenIds }, "other": { "$gte": lastSeenValue } },
{ "limit": 5, "sort": { "other": 1, "_id": 1 } },
function(err,docs) {
docs.forEach(function(doc) {
// do something
if ( lastSeenValue != doc.other ) { // clear on change
lastSeenValue = doc.other;
lastSeenIds = [];
}
lastSeenIds.push(doc._id); // keep a list
});
}
);
这比“跳过”匹配基本查询条件的结果要高效得多。