Does MongoDB's $in clause guarantee order

后端 未结 10 1253
春和景丽
春和景丽 2020-11-22 01:39

When using MongoDB\'s $in clause, does the order of the returned documents always correspond to the order of the array argument?

10条回答
  •  粉色の甜心
    2020-11-22 02:25

    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:

    • 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.

提交回复
热议问题