Search code examples
mongodbmongoosemean-stackmean.io

Mongoose - find documents with maximum no of counts


I am using Mongoose to fetch data from MongoDB. Here is my model.

var EmployeeSchema = new Schema({
      name: String,
      viewCount: { type: Number, default: 0 },
      description: {
        type: String,
        default: 'No description'
      },
      departments: []

    });

I need to find top 5 employees where count(viewCount) is highest order by name.

I am thinking of finding all the employee by using find() & then read viewCount property & produce the result. is there any better way to get the desired result.


Solution

  • All you need here is .sort() and .limit():

    Employee.find().sort({ "viewCount": -1, "name": 1 }).limit(5)
        .exec(function(err,results) {
    
    });
    

    And that is the top 5 employees in views ordered by name after the viewCount.

    If you want them ordered by "name" in your final five, then just sort that result:

    Employee.find().sort({ "viewCount": -1, "name": 1 }).limit(5)
        .exec(function(err,results) {
        // sort it by name
        results.sort(function(a,b) {
            return a.name.localeCompare(b.name);
        });
        // do something with results
    });