在mongodb聚合方法顺序不保持

时间:2018-05-08 08:35:43

标签: node.js mongodb

我有一个这样的集合:

{_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}]

1 个答案:

答案 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)=>{
      ...

$group阶段将始终更改输出文档的顺序,这就是为什么如果您希望响应某个订单,则需要在那里应用任何$sort