How to convert objectid to string

Solution 1:

ObjectId.toString() and ObjectId.valueOf() are in Mongo JavaScript API.

In Python API (with PyMongo) proper way is to use pythonic str(object_id) as you suggested in comment, see documentation on ObjectId.

Solution 2:

ObjectId.toString() returns the string representation of the ObjectId() object.

In pymongo str(o) get a hex encoded version of ObjectId o.

Check this link.

Solution 3:

What works for me is to "sanitize" the output so Pydantic doesn't get indigestion from an _id that is of type ObjectId...here's what works for me... I'm converting _id to a string before returning the output...

# Get One
@router.get("/{id}")
def get_one(id):
    query = {"_id": ObjectId(id)}
    resp = db.my_collection.find_one(query)

    if resp:
        resp['_id'] = str(resp['_id'])
        return resp
    else:
        raise HTTPException(status_code=404, detail=f"Unable to retrieve record")