Vig*_*ian 5 mongodb mongodb-query monk
我想一次从MongoDB中检索数据
我使用限制来限制返回的记录数
router.post('/List', function (req, res) {
var db = req.db;
var collection = db.get('clnName');
collection.find({}, { limit: 5 * req.body.requestCount }, function (e, docs) {
res.json(docs);
});
});
Run Code Online (Sandbox Code Playgroud)
在这里,从客户端我正在递增requestCount变量,以便我获得5的倍数数据.我想要实现的是在第一个请求中获取前5个数据,在第二个请求中获取接下来的5个数据,但是发生了什么,我获得前5个数据,然后获得前10个数据.
我应该做些什么来实现我的需要?
将在mongo游标方法中使用批量大小解决我的问题吗?
那么明显的一个明显的例子就是.skip()用作修饰符.limit()以实现数据的"分页":
collection.find({}, { "limit": 5, "skip": 5 * req.body.requestCount }, function
Run Code Online (Sandbox Code Playgroud)
但更好的是,如果您只是批量处理,只需过滤掉您已经看到的范围.该_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
});
}
);
Run Code Online (Sandbox Code Playgroud)
在下一次将"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
});
}
);
Run Code Online (Sandbox Code Playgroud)
所以将所有结果排除在最后_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
});
}
);
Run Code Online (Sandbox Code Playgroud)
然后在下一次迭代中使用变量:
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
});
}
);
Run Code Online (Sandbox Code Playgroud)
这比通过匹配基本查询条件的结果"跳过"更有效.