1

lets say I have array of users ids

[ 
  '617c4ccfeec17b11c1b9842a', // user A
  '617c4ccfeec17b11c1b98357', // user B
  '617c4ccfeec17b11c1b98359', // user C
  '617c4ccfeec17b11c1b98358', //user D
  '617c4ccfeec17b11c1b9835a', // user E
  '617c4ccfeec17b11c1b9835b', // user F
  '617c4ccfeec17b11c1b9835c'  // user G
]

when I run this query :

let items = await User.find({ _id: { $in: ids }})

this is the result I get db return

[ 
  {userdoc},// user G
  {userdoc},//user F
  {userdoc},// user E
  {userdoc},//user D
  {userdoc},// user C
  {userdoc}, // user B
  {userdoc} // user A
]

why aren't the results in the same of the ids ?

سعيد
  • 1,547
  • 1
  • 14
  • 32

1 Answers1

0

MongoDB has a default sorting if no explicit specified: see the first paragraph from this answear

The default internal sort order (or natural order) is an undefined implementation detail.

and

Without any query criteria, results will be returned by the storage engine in natural order (aka in the order they are found). Result order may coincide with insertion order but this behaviour is not guaranteed and cannot be relied on (aside from capped collections).

this means the result should be the same either you query the documents with $in [A, B, C, D, E, F, G] or $in [G, F, E, D, C, B, A]

If you need explicit ordering, you need to add a $sort operation.

David Laci
  • 146
  • 1
  • 12