Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongodb sort Aggregation in same order ids was passed on filter

I would like to know if its possible to keep the current order of the result the same as it is passed in on the filtering.

So lets say we have an array of IDS:

var arrayValues = [1,3,2]

I would like to aggregate the values but keep the result same order as im passing in the above array.

 var result = Item.aggregate([{ $match: { _id: { $in: arrayValues } }}])

I would want the result in same order as the array values passed in as _id value.

Example Result :

result = [{ _id: 1 },{ _id: 3 },{ _id: 2 }]
like image 856
Ylama Avatar asked Oct 31 '25 19:10

Ylama


1 Answers

You can use indexOfArray for this:

db.collection.aggregate([
  {$match: {_id: {$in: arrayValues}}},
  {$set: {index: {$indexOfArray: [arrayValues, "$_id"]}}},
  {$sort: {index: 1}},
  {$unset: "index"}
])

See how it works on the playground example

like image 158
nimrod serok Avatar answered Nov 02 '25 10:11

nimrod serok