在聚合管道之后$sort将字段添加到文档中,其中包括使用 MongoDb 聚合将其索引包含在排序列表中



我想在聚合管道之后从列表中获取某个用户的顺序$sort

假设我们有一个排行榜,我需要在排行榜中获得我的排名,只有一个查询只获取我的数据

我已经尝试了$addFields和一些查询$map

假设我们有这些文件

/* 1 createdAt:8/18/2019, 4:42:41 PM*/
{
"_id" : ObjectId("5d5963e1c6c93b2da849f067"),
"name" : "x4",
"points" : 69
},
/* 2 createdAt:8/18/2019, 4:42:41 PM*/
{
"_id" : ObjectId("5d5963e1c6c93b2da849f07b"),
"name" : "x24",
"points" : 968
},
/* 3 createdAt:8/18/2019, 4:42:41 PM*/
{
"_id" : ObjectId("5d5963e1c6c93b2da849f06a"),
"name" : "x7",
"points" : 997
},

我想写一个这样的查询

db.table.aggregate(
[
{ $sort : { points : 1 } },
{ $addFields: { order : "$index" } },
{ $match : { name : "x24" } }
]
)

我需要在order字段中注入类似$index

我希望有这样的东西作为回报

{
"_id" : ObjectId("5d5963e1c6c93b2da849f07b"),
"name" : "x24",
"points" : 968,
"order" : 2
}

我需要类似这里返回 2 的结果元数据的东西

/* 2 createdAt:8/18/2019, 4:42:41 PM*/

这种情况的解决方法之一是将所有文档转换为一个数组,从而在$unwind的帮助下使用此数组解析文档的索引,最后根据需要使用字段投影数据。

db.collection.aggregate([
{ $sort: { points: 1 } },
{
$group: {
_id: 1,
register: { $push: { _id: "$_id", name: "$name", points: "$points" } }
}
},
{ $unwind: { path: "$register", includeArrayIndex: "order" } },
{ $match: { "register.name": "x4" } },
{
$project: {
_id: "$register._id",
name: "$register.name",
points: "$register.points",
order: 1
}
}
]);

为了提高效率,您可以根据需要应用限制、匹配和过滤。

最新更新