我知道这是个不好的做法skip为了实现分页,因为当您的数据变得很大时skip开始消耗大量内存。克服这一麻烦的一种方法是利用自然秩序_id字段://Page 1db.users.find().limit(pageSize);//Find the id of the last document in this pagelast_id = ...
//Page 2users = db.users.find({'_id'> last_id}). limit(10);问题是-我对芒果不熟悉,不知道怎样才能做到这一点last_id
1 回答
天涯尽头无女友
TA贡献1831条经验 获得超9个赞
.skip()
.limit()
.skip()
.limit()
db.junk.find().limit(3){ "_id" : ObjectId("54c03f0c2f63310180151877"), "a" : 1, "b" : 1 }{ "_id" : ObjectId("54c03f0c2f63310180151878"), "a" : 4, "b" : 4 }{ "_id" : ObjectId("54c03f0c2f63310180151879"), "a" : 10, "b" : 10 }
var lastSeen = null;var cursor = db.junk.find().limit(3);while (cursor.hasNext()) { var doc = cursor.next(); printjson(doc); if (!cursor.hasNext()) lastSeen = doc._id;}
lastSeen
_id
:
ObjectId("54c03f0c2f63310180151879")
_id
var cursor = db.junk.find({ "_id": { "$gt": lastSeen } }).limit(3);while (cursor.hasNext()) { var doc = cursor.next(); printjson(doc); if (!cursor.hasNext()) lastSeen = doc._id;}{ "_id" : ObjectId("54c03f0c2f6331018015187a"), "a" : 1, "b" : 1 }{ "_id" : ObjectId("54c03f0c2f6331018015187b"), "a" : 6, "b" : 6 }{ "_id" : ObjectId("54c03f0c2f6331018015187c"), "a" : 7, "b" : 7 }
_id
{ "_id": 4, "rank": 3 }{ "_id": 8, "rank": 3 }{ "_id": 1, "rank": 3 } { "_id": 3, "rank": 2 }
var lastSeen = null;var seenIds = [];var cursor = db.junk.find().sort({ "rank": -1 }).limit(2);while (cursor.hasNext()) { var doc = cursor.next(); printjson(doc); if ( lastSeen != null && doc.rank != lastSeen ) seenIds = []; seenIds.push(doc._id); if (!cursor.hasNext() || lastSeen == null) lastSeen = doc.rank;}{ "_id": 4, "rank": 3 }{ "_id": 8, "rank": 3 }
$nin
var cursor = db.junk.find( { "_id": { "$nin": seenIds }, "rank": "$lte": lastSeen }).sort({ "rank": -1 }).limit(2);while (cursor.hasNext()) { var doc = cursor.next(); printjson(doc); if ( lastSeen != null && doc.rank != lastSeen ) seenIds = []; seenIds.push(doc._id); if (!cursor.hasNext() || lastSeen == null) lastSeen = doc.rank;}{ "_id": 1, "rank": 3 } { "_id": 3, "rank": 2 }
lastSeen
seenIds
添加回答
举报
0/150
提交
取消