How to Convert Objectid to String

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.

1

4 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.

0

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.

0

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")

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) }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

David Miller

David Miller

Executive Financial & Market Analyst

David Miller brings 15 years of experience in global economics, personal finance strategy, and market dynamics. He specializes in turning complex economic trends into actionable insights for everyday readers.

Share this article
Twitter Facebook Pinterest