Does MongoDB's $in clause guarantee order

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

    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
    

提交回复
热议问题