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?