我有一个带有 field Played_Frequency 的猫鼬模型,我如何找到播放中编号最高的所有文档中的前 10 个文档
这是我的模型界面:
export interface ITrack {
genre: string;
title: string;
artist: string;
featuring?: string;
duration: string;
coverImage?: string;
image: string;
url: string;
trending?: number;
played_frequency: number;
promoted?: boolean;
likes?: number;
}
和播放频率,会因文档而异,我需要一种方法来搜索所有文档并仅找到 10 个最高播放频率。
虽然@cmgchess 已经在评论中提供了完美的解决方案,但我想讨论一下对于我们有平局的情况的要求的不同解释。
考虑潜在的情况,例如:
[
{
"played_frequency": 1
},
{
"played_frequency": 2
},
{
"played_frequency": 3
},
{
"played_frequency": 4
},
{
"played_frequency": 5
},
{
"played_frequency": 6
},
{
"played_frequency": 7
},
{
"played_frequency": 8
},
{
"played_frequency": 9
},
{
"played_frequency": 10
},
{
"played_frequency": 10
}
]
所以你可以看到
played_frequency
从1到9有9个案例,10有2个案例。
如果您只想返回 10 个文档,即两个 10 和从 9 到 2,您可以使用
$rank
计算排名并选择 rank: {$lte: 10}
db.collection.aggregate([
{
"$setWindowFields": {
"sortBy": {
"played_frequency": -1
},
"output": {
"rank": {
"$rank": {}
}
}
}
},
{
"$match": {
"rank": {
"$lte": 10
}
}
},
{
"$unset": "rank"
}
])
如果你想获取前 10 个
played_frequency
值的文档,即两个 10 和从 9 到 1,你需要使用 $denseRank
db.collection.aggregate([
{
"$setWindowFields": {
"sortBy": {
"played_frequency": -1
},
"output": {
"rank": {
"$denseRank": {}
}
}
}
},
{
"$match": {
"rank": {
"$lte": 10
}
}
},
{
"$unset": "rank"
}
])