Search code examples
pythonmongodbpymongofastapi

Pymongo define list as type of ObjectId for $in query


I have a list of ObjectIds which I want to pass into the following pymongo command to find the documents by their ObjectId

ids = ['62b3221c2db07f9388aa61e9', '62b325f65402e5ceea9a3d4c', '62b48ccee6f77605c2783775']

list(dbusers.find({"_id" : {"$in": ids }}))

However it expects them to be in the format ids = [ObjectId('62b3221c2db07f9388aa61e9'), ObjectId('62b325f65402e5ceea9a3d4c'), ObjectId('62b48ccee6f77605c2783775')]

But I can't seem to get them in this format as they are in a list?


Solution

  • You can convert the object id strings to proper ObjectId objects by giving the object id as a parameter when creating it (ObjectId(<object_id>)).

    To convert your list to a list of ObjectId objects instead of a plain string list, you can use map which invokes a callable on each element in a list and returns an iterator - you can then exhaust this iterator and get a list back by giving it to list:

    from bson.objectId import ObjectId
    
    
    object_id_list = list(map(ObjectId, ids))
    found_users = list(dbusers.find({"_id": {"$in": object_id_list}}))
    

    Since a class works as a callable to instantiate the class, you can give the class as the first argument to map and get objects created as that class back.