在Mongo数据库中,我有一些示例数据,如下所示:
对象1
{
'id': 1,
'name': 'ram',
'age': 25,
'group': 'developer',
'salary': 30000
}
对象2
{
'id': 2,
'name': 'sai',
'age': 27,
'group': 'developer',
'salary': 45000
}
这是mongodb中的一些示例数据,我有很多对象都与员工详细信息有关。
如何从此数据中获得第一或第二或第三高薪以及详细信息。因此,查询应该像是如果我想要第三高薪水,即使薪水发生变化,它也必须给我匹配文档的所有详细信息。 如果薪水增加,则无需更改查询。
答案 0 :(得分:0)
我只是将limit
放在这里,以防万一...不确定您的收藏有多大等。
随便找到:
db.getCollection('<ColName>').find({}).sort({ salary: -1 }).limit(3)
总计:
db.collection.aggregate([
{ $sort: { "salary": -1} },
{ $skip : 2 }, // Skip the first 2 and get the 3rd
{ $limit: 1} // Only get the 3rd
])
您可以测试/查看结果here
答案 1 :(得分:0)
请尝试以下操作:
db.collection.aggregate([{
$project: {
max: {
$max: "$salary"
},
salary: 1
}
}, {
$sort: {
"salary": -1
}
},
{
$limit: 3
}
])
这总是对我有用。
答案 2 :(得分:0)
这是您可以实现的方式:
db.getCollection('tablename').find({}).sort({salary:-1}).toArray();
您的数组的第一项将具有最高薪水,而最后一项将具有最低薪水
答案 3 :(得分:0)
如果要使用以下查询获得第n个最高薪水记录,只需跳过n-1个记录。
db.getCollection('<ColName>').find({}).sort({ salary: -1 }).skip(n-1).limit(1)