Régis B. Régis B. - 9 months ago 58
Python Question

MongoDb: $sort by $in

I am running a mongodb

query with an

collection.find({name: {$in: [name1, name2, ...]}})

I would like the results to be sorted in the same order as my name array:
[name1, name2, ...]
. How do I achieve this?

Note: I am accessing MongoDb through pymongo, but I don't think that's of any importance.

EDIT: as it's impossible to achieve this natively in MongoDb, I ended up using a typical Python solution:

names = [name1, name2, ...]
results = list(collection.find({"name": {"$in": names}}))
results.sort(key=lambda x: names.index(x["name"]))

Answer Source

Impossible. $in operator checks the presence. The list is treated as set.


  • Split for several queries for name1 ... nameN or filter the result the same way. More names - more queries.
  • Use itertools groupby/ifilter. In that case - add the "sorting precedence" flag to every document and match name1 to PREC1, name2 to PREC2, ...., then isort by PREC then group by PREC.

If your collection has the index on "name" field - option 1 is better. If doest not have the index or you cannot create it due to high write/read ratio - option 2 is for you.