Javascript MongoDB:获取集合中元素的索引
我收集了以下格式的文件:Javascript MongoDB:获取集合中元素的索引,javascript,mongodb,Javascript,Mongodb,我收集了以下格式的文件: { “用户”:{“用户名”:“字符串”} “分数”:123 } 我想在集合中查找用户的排名 collection.aggregate([ {$sort:{score:-1}},//按分数降序排序 { $项目:{ 分数:“$score” 排名:{ $indexOfArray:[ “$”,//我不知道在这里放什么 {'user.username':'myUser'} ] } } } ]); 如何将集合视为数组 我在寻找这个结果: [ { “分数”:123, “排名”:
{
“用户”:{“用户名”:“字符串”}
“分数”:123
}
我想在集合中查找用户的排名
collection.aggregate([
{$sort:{score:-1}},//按分数降序排序
{
$项目:{
分数:“$score”
排名:{
$indexOfArray:[
“$”,//我不知道在这里放什么
{'user.username':'myUser'}
]
}
}
}
]);
如何将集合视为数组
我在寻找这个结果:
[
{
“分数”:123,
“排名”:1
}
]
我们可以通过执行自查找来实现这一点。以下查询可以获得预期的输出:
db.collection.aggregate([
{
$match:{
"user.username":"B"
}
},
{
$lookup:{
"from":"my_collection_name",
"let":{
"score":"$score"
},
"pipeline":[
{
$match:{
$expr:{
$gt:["$score","$$score"]
}
}
},
{
$group:{
"_id":null,
"above":{
$sum:1
}
}
}
],
"as":"selfLookup"
}
},
{
$unwind:{
"path":"$selfLookup",
"preserveNullAndEmptyArrays":true
}
},
{
$project:{
"_id":0,
"score":1,
"rank":{
$cond:[
{
$eq:["$selfLookup.above",null]
},
1,
{
$sum:["$selfLookup.above",1]
}
]
}
}
}
]).pretty()
数据集:
{
"_id" : ObjectId("5d657d2d7d0ab652c42315f3"),
"user" : {
"username" : "A"
},
"score" : 123
}
{
"_id" : ObjectId("5d657d2d7d0ab652c42315f4"),
"user" : {
"username" : "B"
},
"score" : 122
}
{
"_id" : ObjectId("5d657d2d7d0ab652c42315f5"),
"user" : {
"username" : "C"
},
"score" : 121
}
{ "score" : 122, "rank" : 2 }
输出:
{
"_id" : ObjectId("5d657d2d7d0ab652c42315f3"),
"user" : {
"username" : "A"
},
"score" : 123
}
{
"_id" : ObjectId("5d657d2d7d0ab652c42315f4"),
"user" : {
"username" : "B"
},
"score" : 122
}
{
"_id" : ObjectId("5d657d2d7d0ab652c42315f5"),
"user" : {
"username" : "C"
},
"score" : 121
}
{ "score" : 122, "rank" : 2 }
说明:我们正在计算得分高于搜索用户得分的用户数(本例中为“B”)。如果未找到任何记录,则秩为1,否则秩将为count+1。结果是什么json?@Caconde updated当我运行此操作时,第一个聚合阶段(匹配)将集合减少为1项,因此每个秩为1。否。第一个聚合阶段获取具有搜索用户名的记录。从那张记录中,我们也得到了分数。然后,该分数用于在同一集合中查找(第二个聚合阶段)。无论我输入哪个用户名,我的排名都是第一。当我将
foo:'$selfLookup.over'
添加到我的$project
中时,它似乎不存在。您可以添加一些示例数据吗?您正在更改查找权限中的集合名称吗?在from
字段中?