I had the same problem and my solution was to create a hash map to do the mapping between my array of ids (my query) and my array of results from MongoDB.
The extra work is to browse the array of results and to insert, for each item, a new key-value pair: the key is the ID and the value is the result object.
Then, when I want to browse my results in the same order as my query was, I can use the hashmap to retrieve the correct object. No sorting, and no fancy Mongo DB option.
In Javascript it would be something like:
//The order you want
var queryIds = [ 8, 5, 3, 7 ];
//The results from MongoDB in an undefined order
var resultsFromMongoDB = [
{_id: 7, data: "d" },
{_id: 8, data: "a" },
{_id: 5, data: "b" },
{_id: 3, data: "c" },
];
//The function to create a hashmap to do the mapping
function createHashOfResults( results ){
var hash = {};
for( var i = 0 ; i < results.length ; i++ ){
var item = results[i];
var id = item._id;
hash[ id ] = item;
}
return hash;
}
//Let's build the hashmap
var hash = createHashOfResults( resultsFromMongoDB );
//Now we can display the results in the order we want
for( var i = 0 ; i < queryIds.length ; i++ ){
var queryId = queryIds[i];
var result = hash[queryId];
console.log( result.data );
}
This will display:
a
b
c
d