Home > Net >  Mongodb sort Aggregation in same order ids was passed on filter
Mongodb sort Aggregation in same order ids was passed on filter

Time:08-03

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

CodePudding user response:

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

  • Related