我有一個MongoDB的集合,它看起來像這樣:如何獲得mongoDB集合的排名位置?
[{
"_id": 1,
"name": "John Doe",
"company": "Acme",
"email": "[email protected]",
"matches": [171844, 169729, 173168, 174310, 168752, 174972, 172959, 169546]
}, {
"_id": 2,
"name": "Bruce Wayne",
"company": "Wayne Enterprises",
"email": "[email protected]",
"matches": [171844, 232333, 233312, 123456]
}, {
"_id": 3,
"name": "Tony Stark",
"company": "Stark Industries",
"email": "[email protected]",
"matches": [173844, 155729, 133168, 199310, 132752, 139972]
}, {
"_id": 4,
"name": "Clark Kent",
"company": "Daily Planet",
"email": "[email protected]",
"matches": [169729, 174310, 168752]
}, {
"_id": 5,
"name": "Lois Lane",
"company": "Daily Planet",
"email": "[email protected]",
"matches": [172959, 169546]
}]
我需要得到用戶的過濾列表,但與顯示了基於「匹配」的數量用戶的「排行榜」上排名的關鍵記錄它有。 應該有一個「全球排名」職位和一個「公司排名」職位。
期望的結果應該是這樣的(對於一個例子公司=「每日星球」過濾):
[ { _id: 4,
name: 'Clark Kent',
company: 'Daily Planet',
email: '[email protected]',
points: 3,
globalRank: 4,
companyRank: 1
},
{ _id: 5,
name: 'Lois Lane',
company: 'Daily Planet',
email: '[email protected]',
points: 2,
globalRank: 4,
companyRank: 2
} ]
注意,克拉克·肯特排名在全球排名第四,因爲他有3場比賽( John Doe,Bruce Wayne和Tony Stark比他擁有更多的比賽),並且在公司排名中排名第一,因爲他擁有比任何Daily Planet用戶更多的比賽。
但是,即使經過幾天的研究,我也找不到辦法做到這一點。 (我甚至不知道如何僅進行全球排名或公司排名)。
我使用如下下面總管道:
[{
$match: {
company: "Daily Planet"
}
}, {
$project: {
_id: 1,
name: "$name",
company: "$company",
email: "$email",
points: {
$size: "$matches"
}
}
}, {
$sort: {
points: -1
}
}]
但這並不返回由點排列名次,只記錄。
關於如何解決這個問題或者如何以不同方式解決問題的想法?
什麼的MongoDB的版本? – hyades