2

I have a collection in MongoDB in which I need to fetch multiple documents at a time but I would like them to be ordered based on the order of ids that I pass in. For example, if I pass in a list of ids: [1, 5, 3], I want to receive the corresponding documents in that exact order: [object with id 1, object with id 5, object with id 3].

I have tried using the $in operator but this typically returns documents ordered by when they were created. So if I created objects in the following order: [object with id 1, object with id 3, object with id 5] and I use the $in operator with the following ids: [1, 5, 3], I still receive objects in the following order: [object with id 1, object with id 3, and object with id 5].

Is there a way to do this in MongoDB?

prasad_
  • 12,755
  • 2
  • 24
  • 36
namu24
  • 51
  • 2
  • The find query method returns a _cursor_. You can apply the [cursor#sort](https://docs.mongodb.com/manual/reference/method/cursor.sort/#cursor.sort) on the `id` field. – prasad_ Jul 22 '20 at 01:42
  • https://stackoverflow.com/a/42293303/19084052 you might interested in .it was useful for me – Faruk Önder Beyazit May 10 '22 at 08:59

0 Answers0