获取基于多个字段的前100个文档



我正试图根据几个字段的总和从数据库中获取100个文档。

数据与此类似:

{
"userID": "227837830704005140",
"shards": {
"ancient": {
"pulled": 410
},
"void": {
"pulled": 1671
},
"sacred": {
"pulled": 719
}
}
}

我想把";"拉动";3种类型的碎片的数量,然后用它来确定前100名。

我在nodejs:中尝试过

let top100: IShardData[] = await collection.find<IShardData>({}, {
projection: {
"shards.ancient.pulled": 1, "shards.void.pulled": 1, "shards.sacred.pulled": 1, orderBySumValue: { $add: ["$shards.ancient.pulled", "$shards.void.pulled", "$shards.sacred.pulled"] }
}, sort: { orderBySumValue: 1 }, limit: 100
}).toArray()

这将连接到DB,获得正确的集合,并且似乎正确地汇总了值,但并没有根据字段的总和对前100名进行排序。我将此作为代码的基础:https://www.tutorialspoint.com/mongodb-order-by-two-fields-sum

不确定我需要做什么才能让它发挥作用。感谢您的帮助。

提前感谢!

这里有一种使用aggregation管道的方法。

db.collection.aggregate([
{
// create new field for the sum
"$set": {
"pulledSum": {
"$sum": [
"$shards.ancient.pulled",
"$shards.void.pulled",
"$shards.sacred.pulled"
]
}
}
},
{
// sort on the sum
"$sort": {
"pulledSum": -1
}
},
{
// limit to the desired number
"$limit": 10
},
{
// don't return some fields
"$unset": [
"_id",
"pulledSum"
]
}
])

在mongoplayground.net上试试。

sort应该用美元符号书写。

$sort: { orderBySumValue: 1 }

最新更新