Does MongoDB’s $in clause guarantee order

Another way using the Aggregation query only applicable for MongoDB verion >= 3.4

The credit goes to this nice blog post.

Example documents to be fetched in this order –

var order = [ "David", "Charlie", "Tess" ];

The query –

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.

Leave a Comment

tech