0

In Mongo db I have some sample data as follows:

Object 1

{
 'id': 1,
 'name': 'ram',
 'age': 25,
 'group': 'developer',
 'salary': 30000
}

Object 2

{
 'id': 2,
 'name': 'sai',
 'age': 27,
 'group': 'developer',
 'salary': 45000
}

This is some sample data in the mongodb and I have so many objects all related to employee details.

From this data how to get the 1st or 2nd or 3rd highest salary and the details. So query should be like if i want 3rd highest salary it has to give me the all the details of matching document even if the salary is changed. The query should not need to be changed if the salary is increased.

Akrion
  • 18,117
  • 1
  • 34
  • 54
Anjansai
  • 47
  • 6

4 Answers4

0

I just put limit there just in case ... not sure how big is your collection etc.

With just find:

db.getCollection('<ColName>').find({}).sort({ salary: -1 }).limit(3)

With aggregate:

db.collection.aggregate([
  { $sort: { "salary": -1} },
  { $skip : 2 },  // Skip the first 2 and get the 3rd
  { $limit: 1}    // Only get the 3rd
])

You can test/see the result here

Akrion
  • 18,117
  • 1
  • 34
  • 54
0

Please try this:

db.collection.aggregate([{
    $project: {
      max: {
        $max: "$salary"
      },
      salary: 1
    }
  }, {
    $sort: {
      "salary": -1
    }
  },
  {
    $limit: 3
  }
])

This always works for me.

Patrick Mevzek
  • 10,995
  • 16
  • 38
  • 54
Raj Jaril
  • 376
  • 1
  • 16
0

Here is how you can achieve that:

db.getCollection('tablename').find({}).sort({salary:-1}).toArray();

Your first item of the array will have the max salary while the last will have the min salary

Nico Haase
  • 11,420
  • 35
  • 43
  • 69
Shantanu Madane
  • 617
  • 5
  • 14
0

Just skip n-1 records if want nth highest salary record using following query.

db.getCollection('<ColName>').find({}).sort({ salary: -1 }).skip(n-1).limit(1)