I am running a mongodb find
query with an $in
operator:
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"]))
Impossible. $in operator checks the presence. The list is treated as set.
Options:
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.