如何在Mongoose中获得文档的中间部分?
集合架构:
{
_id: string,
points: number
}
我想要按点排序,然后按_id匹配,最终结果获取前50名和后50名,Matched_id为中心.还包括基于排序的索引将很好,但不是必要的.
如何在Mongoose中获得文档的中间部分?
集合架构:
{
_id: string,
points: number
}
我想要按点排序,然后按_id匹配,最终结果获取前50名和后50名,Matched_id为中心.还包括基于排序的索引将很好,但不是必要的.
从MongoDB版本5.0开始,一种 Select 是使用$setWindowFields
:
db.collection.aggregate([
{$setWindowFields: {
sortBy: {points: -1},
output: {
neighbors: {
$push: "$$ROOT",
window: {documents: [-N, N]}
}
}
}},
{$match: {_id: _id}},
{$project: {neighbors: 1, _id: 0}},
{$unwind: {path: "$neighbors", includeArrayIndex: "index"}},
{$project: {
_id: "$neighbors._id",
points: "$neighbors.points",
index: 1
}}
])
看看它在playground example号公路上是如何工作的
_id
,然后在$match
之后使用$lookup
EDIT:如果您想要根据整个排序进行索引:
$setWindowFields
上添加另一个输出字段以设置索引$reduce
设置为我们使用的所有项目编制索引db.collection.aggregate([
{$setWindowFields: {
sortBy: {points: -1},
output: {
neighbors: {
$push: "$$ROOT",
window: {documents: [-N, N]}
},
index: {
$sum: 1,
window: {documents: ["unbounded", "current"]}
}
}
}},
{$match: {_id: _id}},
{$project: {
neighbors: {$reduce: {
input: "$neighbors",
initialValue: [],
in: {$concatArrays: [
"$$value",
[{$mergeObjects: [
"$$this",
{index: {$add: [{$subtract: [{$size: "$$value"}, N + 1]}, "$index"]}}
]}]
]}
}},
_id: 0
}},
{$unwind: "$neighbors"},
{$replaceRoot: {newRoot: "$neighbors"}}
])
看看它在playground example号公路上是如何工作的