As noted, the order of the arguments in the array of an $in clause does not reflect the order of how the documents are retrieved. That of course will be the natural order or by the selected index order as shown.
If you need to preserve this order, then you basically have two options.
So let's say that you were matching on the values of _id in your documents with an array that is going to be passed in to the $in as [ 4, 2, 8 ].
Approach using Aggregate
var list = [ 4, 2, 8 ];
db.collection.aggregate([
// Match the selected documents by "_id"
{ "$match": {
"_id": { "$in": [ 4, 2, 8 ] },
},
// Project a "weight" to each document
{ "$project": {
"weight": { "$cond": [
{ "$eq": [ "$_id", 4 ] },
1,
{ "$cond": [
{ "$eq": [ "$_id", 2 ] },
2,
3
]}
]}
}},
// Sort the results
{ "$sort": { "weight": 1 } }
])
So that would be the expanded form. What basically happens here is that just as the array of values is passed to $in you also construct a "nested" $cond statement to test the values and assign an appropriate weight. As that "weight" value reflects the order of the elements in the array, you can then pass that value to a sort stage in order to get your results in the required order.
Of course you actually "build" the pipeline statement in code, much like this:
var list = [ 4, 2, 8 ];
var stack = [];
for (var i = list.length - 1; i > 0; i--) {
var rec = {
"$cond": [
{ "$eq": [ "$_id", list[i-1] ] },
i
]
};
if ( stack.length == 0 ) {
rec["$cond"].push( i+1 );
} else {
var lval = stack.pop();
rec["$cond"].push( lval );
}
stack.push( rec );
}
var pipeline = [
{ "$match": { "_id": { "$in": list } }},
{ "$project": { "weight": stack[0] }},
{ "$sort": { "weight": 1 } }
];
db.collection.aggregate( pipeline );
Approach using mapReduce
Of course if that all seems to hefty for your sensibilities then you can do the same thing using mapReduce, which looks simpler but will likely run somewhat slower.
var list = [ 4, 2, 8 ];
db.collection.mapReduce(
function () {
var order = inputs.indexOf(this._id);
emit( order, { doc: this } );
},
function() {},
{
"out": { "inline": 1 },
"query": { "_id": { "$in": list } },
"scope": { "inputs": list } ,
"finalize": function (key, value) {
return value.doc;
}
}
)
And that basically relies on the emitted "key" values being in the "index order" of how they occur in the input array.
So those essentially are your ways of maintaining the order of a an input list to an $in condition where you already have that list in a determined order.
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:
The above code is using the Mongo Node driver and not Mongoose
The idArray is an array of ObjectId
I haven't tested the performance of this method vs the sort, but if you need to manipulate each returned item (which is pretty common) you can do it in the map callback to simplify your code.
I know this is an old thread, but if you're just returning the value of the Id in the array, you may have to opt for this syntax. As I could not seem to get indexOf value to match with a mongo ObjectId format.
obj.map = function() {
for(var i = 0; i < inputs.length; i++){
if(this._id.equals(inputs[i])) {
var order = i;
}
}
emit(order, {doc: this});
};
I know this question is related to Mongoose JS framework, but the duplicated one is generic, so I hope posting a Python (PyMongo) solution is fine here.
things = list(db.things.find({'_id': {'$in': id_array}}))
things.sort(key=lambda thing: id_array.index(thing['_id']))
# things are now sorted according to id_array order
var query = [
{$match: {name: {$in: order}}},
{$addFields: {"__order": {$indexOfArray: [order, "$name" ]}}},
{$sort: {"__order": 1}}
];
var result = db.users.aggregate(query);
Another quote from the post explaining these aggregation operators used -
The "$addFields" stage is new in 3.4 and it allows you to "$project" new fields to existing documents without knowing all the other existing fields. The new "$indexOfArray" expression returns position of particular element in a given array.
Basically the addFields operator appends a new order field to every document when it finds it and this order field represents the original order of our array we provided. Then we simply sort the documents based on this field.
An easy way to order the result after mongo returns the array is to make an object with id as keys and then map over the given _id's to return an array that is correctly ordered.
For any newcomers here is an short and elegant solution to preserve the order in such cases as of 2021 and using MongoDb 3.6 (tested):
const idList = ['123', '124', '125']
const out = await db
.collection('YourCollection')
.aggregate([
// Change uuid to your `id` field
{ $match: { uuid: { $in: idList } } },
{
$project: {
uuid: 1,
date: 1,
someOtherFieldToPreserve: 1,
// Addding this new field called index
index: {
// If we want index to start from 1, add an dummy value to the beggining of the idList array
$indexOfArray: [[0, ...idList], '$uuid'],
// Otherwise if 0,1,2 is fine just use this line
// $indexOfArray: [idList, '$uuid'],
},
},
},
// And finally sort the output by our index
{ $sort: { index: 1 } },
])