$in operator ordering

Hi Team I am using the $in operator for find and my query will be like $in[uuid5,uuid1,uuid2] and I want to acheive the same order in my response which i am not getting. Can you help on this ?

Hello @Subham_Kumar_Sahu, Welcome to the MongoDB Community Forum,

The $in operator won’t preserve the order or documents in response as passed in the match.

You have to try an aggregation query with some additional stage for that operation, something like this, Consider _id is your matching property,

  • $match stage to match your condition
  • $addFields to introduce a new field index
  • $indexOfArray to find the index of the current document’s _id property in your match array
  • $sort to sort the result by index field in ascending order
var matchArray = [uuid5,uuid1,uuid2];
  { $match: { _id: { $in: matchArray } } },
    $addFields: {
      index: {
        $indexOfArray: [matchArray, "$_id"]
  { $sort: { index: 1 } }

Look at a similar question for more information,


thanks @turivishal the above solution works for me

1 Like

I would like to offer an alternative that may be better and may be worst than turivishal’s solution. I certainly do not want to discredit his solution. But I like to experiment as a mental challenge.

My alternative solution uses $documents and $lookup and does not require $sort.

1 Like