When using MongoDB\'s $in clause, does the order of the returned documents always correspond to the order of the array argument?
Similar to JonnyHK's solution, you can reorder the documents returned from find
in your client (if your client is in JavaScript) with a combination of map
and the Array.prototype.find
function in EcmaScript 2015:
Collection.find({ _id: { $in: idArray } }).toArray(function(err, res) {
var orderedResults = idArray.map(function(id) {
return res.find(function(document) {
return document._id.equals(id);
});
});
});
A couple of notes:
idArray
is an array of ObjectId
map
callback to simplify your code.