mongodb $ in应该以数组的相同顺序获取记录

时间:2019-01-14 06:11:21

标签: node.js mongodb

我有一个Ids数组,我想从mongodb集合中获取对该数组的记录。但是现在它提供了数据,但是这不会保持数组顺序的顺序。

var array = ['gshbfewueinbsdeipp38x', 'ou38xvbad084jgmblaxzp', 'plaz3tc61bs0cmzpIKtq', '1az94ocnmzb36GH92skaw63bx'];

在我的代码中:

db.collection("fruits").aggregate([{'$match':{_id:array}}])

实际结果:

[{_id: ObjectId('ou38xvbad084jgmblaxzp'),name:"Apple"},{_id: ObjectId('1az94ocnmzb36GH92skaw63bx'),name:"mango"},{_id: ObjectId('plaz3tc61bs0cmzpIKtq'),name:"orange"},{_id: ObjectId('gshbfewueinbsdeipp38x'),name:"Banana"}]

预期结果:

[{_id: ObjectId('gshbfewueinbsdeipp38x'),name:"Banana"},{_id: ObjectId('ou38xvbad084jgmblaxzp'),name:"Apple"},{_id: ObjectId('plaz3tc61bs0cmzpIKtq'),name:"orange"},{_id: ObjectId('1az94ocnmzb36GH92skaw63bx'),name:"mango"}]

这将不会获得与上述数组相同的顺序。请在上面帮助我。

谢谢

1 个答案:

答案 0 :(得分:1)

请尝试以下操作:-

var array = ['gshbfewueinbsdeipp38x', 'ou38xvbad084jgmblaxzp','plaz3tc61bs0cmzpIKtq','1az94ocnmzb36GH92skaw63bx'];
projection = { 
    "$addFields" : { 
        "__custom_order" : { "$indexOfArray" : [ array, "$_id" ] } 
    } 
},
sort = { "$sort" : { "__custom_order" : 1 } };
db.collection("fruits").aggregate([ projection, sort]);