ArUn
ArUn

Reputation: 1337

Pagination in Mongodb Nodejs

is there any method to get the total count of document in the find operation along with the skip and limit in the query in 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);

     });
});

Upvotes: 2

Views: 3575

Answers (3)

edam
edam

Reputation: 958

I assume "uniqueId" is not the primary key!

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 Aggregate Count

Upvotes: 4

Quoc Lee
Quoc Lee

Reputation: 39

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) {
    // ... 
});

The mongoose-pagination is good

Upvotes: 0

Daphoque
Daphoque

Reputation: 4678

You can't filter with skip and limit and have the total count in only one request if you use .find..

If you want to retrieve documents, filter, and perform count operation in only one request you have to use aggregate

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

Upvotes: 1

Related Questions