gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 09:47:27 27 4
gpt4 key购买 nike

我想在 $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 字段中注入(inject) $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
}
}
]);

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

关于mongodb - 在 $sort 聚合管道之后向文档添加字段,该管道使用 MongoDb 聚合将其索引包含在排序列表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57546357/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com