Sajeetharan
Sajeetharan

Reputation: 222722

How to retrieve top 5 results and total count with mongoose and node?

I have the collection with fields as follows,

enter image description here

i use the following method to query the necessary data,

query: function (model, conditon, options) {
            console.log(conditon, options);
            return new Promise(function (resolve, reject) {
                options = options || {};

                model.find(conditon, {}, options).exec(function (error, data) {
                    if (error)
                        reject(error);
                    resolve(data);
                })
            })
        }

How can i change the above to get total count of records and the top 5 elements at once?

Upvotes: 3

Views: 1743

Answers (2)

Naeem Shaikh
Naeem Shaikh

Reputation: 15725

You can use aggregates to get documents and count in the same result.

model.aggregate( [
   { $match:conditon},
   { $group: { _id: null, count: { $sum: 1 }, results:{$push:'$$ROOT'} } },
   { $project: {count:1, results:{ $slice: 5}}}
], function(error, data){
      if (error)
          reject(error);
      resolve(data);
} );

Upvotes: 2

Simran
Simran

Reputation: 2830

model.aggregate( [
   { $match: condition } },  // this stage will exclude documents on basis of match
   { $count:"Total Count"}, // this stage gives count of remaining documents after $match
   { $limit: 5} // this will limit your response to 5 documents
], function(error, data){
      if (error)
          reject(error);
      resolve(data);
} );

This query will give you result on basis of your condition then counts number of documents and then limit your response.

Upvotes: 1

Related Questions