Mongodb query to sort objects with a list of ID’s

  aggregation-framework, mongodb, pymongo, python

I have a function that returns a list of ID’s.
The list of ID’s is important and I need to extract the data from collection and have it sorted in the same order that the list is in.
For e.g: My list of ID’s is: [id8,id5,id4,id9,id3].
I run a pymongo query like: db.collection.find({"_id":{"$in":[ObjectId(i) for i in list]}}).
However this messes up the list order. I need to get the objects in the same order like id8,id5,id4,id9,id3.

I tried using an aggregate function too:

db.collection.aggregate([
            {"$match":{"_id": {"$in": [ObjectId(_id) for _id in list]}}},
            { "$addFields" : {"__order":{"$indexOfArray":[list, "$_id"]}}},
            { "$sort" : { "__order" : 1 } }
        ])

However, even this returns the same order of objects.

Source: Python Questions

LEAVE A COMMENT