說我有一個MongoDB的集合與文檔有關員工:MongoDB聚合:如何查詢每組有限數量的「頂級」文檔?
{
name : "John Doe",
department : "Finance",
salary : 100
}
我如何可以查詢每個部門的最高薪水的員工X?
編輯
,只讓自己多一點明確的,這就是我想達到的效果:
db.collection.aggregate(
{$sort : {salary : -1}},
{$group : {
_id : "$department"
employees : {$addToSet : "$name"}
},
{$project : {employees : {$slice : X}}}
)
但這並不原因有二:
1 。$ addToSet不保證輸出集的任何排序(至少根據documentation)。
2. $slice doesn't work in the aggregation framework。
我不認爲這是可能在一個單一的查詢/聚合,因爲它需要多個傳遞來解決答案(首先得到不同的部門,然後...)。 – WiredPrairie