我有一个这样的集合:
{_id:ObjectId("5aa59c8411c5de25042a06fd"),
id: Y19rvB489or4mvtxAAAC,
score: 2
}
{_id:ObjectId("5aa59c8b11c5de25042a06fe"),
id: Y19rvB489or4mvtxAAAC,
score: 4
}
{_id:ObjectId("5aa59c8411c5de25042a0hehb"),
id: Y19rvB489or4mvtxAAAD,
score: 3
}
{_id:ObjectId("5aa59c8411c5de25042a06fd"),
id: Y19rvB489or4mvtxAAAD,
score: 2
}
{_id:ObjectId("5aa59c8411c5de25042a0j3bb"),
id: Y19rvB489or4mvtxAAAE,
score: 5
}
{_id:ObjectId("5aa59c8411c5de25042a06fd"),
id: Y19rvB489or4mvtxAAAE,
score: 4
}
{_id:ObjectId("5aa59c8411c5de250wer46fs"),
id: Y19rvB489or4mvtxAAAF,
score: 2
}
{_id:ObjectId("5aa59c8411c5de250423e6fg"),
id: Y19rvB489or4mvtxAAAF,
score: 2
}
{_id:ObjectId("5aa59c8411c5de25042a06fd"),
id: Y19rvB489or4mvtxAAAC,
score: 2
}
{_id:ObjectId("5aa59c8411c5de25042a06fd"),
id: Y19rvB489or4mvtxAAAC,
score: 2
}
{_id:ObjectId("5aa59c8411c5de25042a06fd"),
id: Y19rvB489or4mvtxAAAC,
score: 2
}
我正在使用此查询,以便我可以按照我想要的顺序获取结果,即参数中传递的顺序。这里data.enemy_id [1] = Y19rvB489or4mvtxAAAD,data.enemy_id [2] = Y19rvB489or4mvtxAAAC,data.id = Y19rvB489or4mvtxAAAE
var order =[data.enemy_id[1],data.enemy_id[0],data.id];
db.collection('Scores').aggregate([
{$match: {id:{$in:order}}},
{$addFields: {"__order": {$indexOfArray: [order, "$id" ]}}},
{$sort: {"__order": 1}},
{$group: {_id:'$id',score:{$max:'$score'}}},
{$project: {_id:0,score:1}}
]).toArray().then((docs)=>{
var score1 = JSON.stringify(docs,undefined,2);
var score1 = JSON.parse(score1);
console.log(score1);
我想以这种方式获取结果:;即。 id' Y19rvB489or4mvtxAAAD'的最高分。 ,' Y19rvB489或4mvtxAAAC' Y19rvB489或4mvtxAAAE'按此顺序。但我无法以所需的有序方式获取它 [{得分:3},{得分:4},{分数:5}]
答案 0 :(得分:1)
$sort
位置错误。只有在<{>} $group
之后订购才变得非常重要:
var order =[data.enemy_id[1],data.enemy_id[0],data.id];
db.collection('Scores').aggregate([
{$match: {id:{$in:order}}},
{$addFields: {"__order": {$indexOfArray: [order, "$id" ]}}},
// {$sort: {"__order": 1}}, // <-- remove this one
// Keep the __order field in the next stage
{$group: {_id:'$id',score:{$max:'$score'}, "__order": { "$first": "$__order" } }},
{$sort: {"__order": 1}}, // <-- move to here to actually sort
{$project: {_id:0,score:1}}
]).toArray().then((docs)=>{
...