How to convert objectid to string

Simon picture Simon · Oct 14, 2014 · Viewed 60.9k times · Source

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.

Answer

rutsky picture rutsky · Mar 12, 2015

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.