问题
I need to find the nth highest salary in a mongodb from Employees collection. also would be really helpful if someone could gimme an idea of applying joins in mongodb.
回答1:
This should work
db.Employees.find({}).sort({"Emp salary":-1}).limit(1) //for first highest salary
db.Employees.find({}).sort({"Emp salary":-1}).skip(1).limit(1) // for second highest salary
Similarly you can do db.Employees.find({}).sort({"Emp salary":-1}).skip(nthVarible - 1).limit(1)
.
回答2:
Try this out:
db.salary.find({}).sort({s:-1}).skip(1).limit(1);
For your second requirement - MongoDB is noSQL DB, not a transnational DB. It does not support joins.
回答3:
I found a two-step process to do it. it will work in the scenario if there are multiple records with salary same as highest.
Records I have
{ "_id" : ObjectId("5cc04b02536dc2e493697b4e"), "name" : "Ankit" }
{ "_id" : ObjectId("5cc0504a536dc2e493697b50"), "name" : "Ankit", "salary" : 1000, "email" : "a@b.com", "joining_date" : ISODate("2019-04-24T12:02:18.528Z") }
{ "_id" : ObjectId("5cc0504a536dc2e493697b51"), "name" : "Priya", "salary" : 1300, "email" : "p@b.com", "joining_date" : ISODate("2019-04-24T12:02:18.528Z") }
{ "_id" : ObjectId("5cc0504a536dc2e493697b52"), "name" : "Raj", "salary" : 1200, "email" : "rj@b.com", "joining_date" : ISODate("2019-04-24T12:02:18.528Z") }
{ "_id" : ObjectId("5cc0504a536dc2e493697b53"), "name" : "Vishu", "salary" : 1500, "email" : "v@b.com", "joining_date" : ISODate("2019-04-24T12:02:18.528Z") }
{ "_id" : ObjectId("5cc0504a536dc2e493697b54"), "name" : "Rahul", "salary" : 2000, "email" : "ra@b.com", "joining_date" : ISODate("2019-04-24T12:02:18.528Z") }
{ "_id" : ObjectId("5cc08b5d536dc2e493697b57"), "name" : "Tushar", "salary" : 2000, "email" : "tu@b.com", "joining_date" : ISODate("2019-04-24T16:14:21.061Z") }
Find distinct salaries and store in a variable
sal = db.employee.distinct("salary").sort()
Output: [ 1000, 1200, 1300, 1500, 2000 ]
You can get the second highest salary from this array itself. Below query will give you the record with that salary
db.employee.find({salary:{$lt:sal[sal.length-1]}}).sort({"salary":-1}).limit(1)
Output:
{ "_id" : ObjectId("5cc0504a536dc2e493697b53"), "name" : "Vishu", "salary" : 1500, "email" : "v@b.com", "joining_date" : ISODate("2019-04-24T12:02:18.528Z") }
来源:https://stackoverflow.com/questions/32822058/mongodb-how-to-find-nth-highest-salary-from-collection