0

I have array of Ids and I want to get record from mongodb collection against the array. But now its gives data but this will not maintain the order with array order.

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

In my code:

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

Actual Result:

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

Expected Result:

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

This will not get the same order of above array. Please help me on above.

Thanks

Vipul Bhagwat
  • 49
  • 1
  • 7

1 Answers1

1

Please try this:-

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