在Mongodb Nodejs中分页

是否有任何方法来获得查找操作中的文档总数以及MongoDB查询中的跳过和限制

MongoClient.connect(Config.dbURI, function (err, db) { if (!err) { console.log("We are connected"); console.log(uniqueId) db.collection(dbName).find({'uniqueId': uniqueId, 'isDeleted': false}) .sort({modifiedDateISO: -1}) .limit(parseInt(limit)) .skip(parseInt(limit * page)) .toArray((errFindChat, dataFindChat) => { console.log(errFindChat, dataFindChat); }); }); 

如果您使用.find,则无法使用跳过和限制进行过滤,并且只有一个请求中的总数。

如果您想要检索文档,筛选和执行计数操作只需要一个请求,您必须使用聚合

 db.coll.aggregate([ {$match: your find conditions}, {$group/project: your count operations, etc....}, {$skip: skip}, // pagination skip {$limit: limit}, // pagination limit ... ]); 

我假设“uniqueId”不是主键!

 MongoClient.connect(Config.dbURI, function (err, db) { if (!err) { console.log("We are connected"); console.log(uniqueId) db.collection("collname").aggregate( [ { "$match": { "uniqueId": uniqueId, 'isDeleted': false} }, { "$count": "total" }, { "$sort" : {"modifiedDateISO": -1 }, { "$limit": parseInt(limit) }, { "$skip" : parseInt(limit * page) } ] ).toArray((errFindChat, dataFindChat) => { console.log(errFindChat, dataFindChat); }); } }); 

MongoDB聚合计数

 var query = {}; // Your condition var options = { select: 'title date author', sort: { date: -1 }, populate: 'author', lean: true, offset: 20, limit: 10 }; Book.paginate(query, options).then(function(result) { // ... }); 

mongoose分页是好的