Does MongoDB's $in clause guarantee order

后端 未结 10 1441
春和景丽
春和景丽 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:15

    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.

提交回复
热议问题