85

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.

Andrey Korneyev
  • 26,353
  • 15
  • 70
  • 71
Simon
  • 1,033
  • 1
  • 8
  • 16

7 Answers7

132

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.

rutsky
  • 3,900
  • 2
  • 31
  • 30
20

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.

Kaushal
  • 908
  • 1
  • 8
  • 19
4

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")
John D. Aynedjian
  • 639
  • 1
  • 6
  • 4
2

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) }
Evandro Pomatti
  • 13,341
  • 16
  • 97
  • 165
2

In python (Pymongo) there's no inbuilt method to do it so iterate over the result you fetched from db and then typecast _id to str(_id)

result = collection.find({query})

for docs in result:
    docs[_id] = str(docs[_id])
Fedor
  • 17,146
  • 13
  • 40
  • 131
0

This is an old thread, but as the existing answers didn't help me:

Having run

new_object = collection.insert_one(doc)

I was able to get the ObjectID with the inserted_id property:

print(f"{new_object.inserted_id}")
DobbyTheElf
  • 604
  • 6
  • 21
-2

first you have to assign the Object Id value to a variable for example:

let objectId = ObjectId("543b591d91b9e510a06a42e2");

then use the toString method like this

let id = objectId.toString();
  • This would only work on JavaScript but assuming one is working with Python then objectID won't have toString(). If using python just do str(ObjectId) – user8291021 Mar 01 '23 at 06:22