I want to get the string character from an ObjectId object. I use pymongo.
eg: ObjectId("543b591d91b9e510a06a42e2"), I want to get "543b591d91b9e510a06a42e2".
I see the doc, It says ObjectId.toString(), ObjectId.valueOf().
So I make this code: from bson.objectid import ObjectId.
But when I use ObjectId.valueOf(), It shows:
'ObjectId' object has no attribute 'valueOf'.
How can I get it? Thanks.
14 Answers
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.
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.
0What 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") Use str(ObjectId), as already mentined in the comment by @Simon.
@app.route("/api/employee", methods=['POST'])
def create_employee(): json = request.get_json() result = employee.insert_employee(json) return { "id": str(result.inserted_id) }