Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 654
Simon Avatar asked Oct 14 '14 06:10

Simon


People also ask

What datatype is ObjectId?

Binary JSON (BSON) BSON provides additional data types and ordered fields to allow for efficient support across a variety of languages. One of these additional data types is ObjectId.

How do you find the object ID of a string?

Documentation of v4 (right now it's latest version) MongoDB NodeJS Driver says: Method toHexString() of ObjectId returns the ObjectId id as a 24 character hex string representation. Show activity on this post. In Mongoose, you can use toString() method on ObjectId to get a 24-character hexadecimal string.

How many bytes is ObjectId?

An ObjectId is a 12-byte unique identifier consisting of: a 4-byte value representing the seconds since the Unix epoch, a 5-byte random value, a 3-byte counter, starting with a random value.

What is ObjectId?

An ObjectID is a unique, not null integer field used to uniquely identify rows in tables in a geodatabase. ObjectIDs are limited to 32-bit values, which store a maximum value of 2,147,483,647.


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

like image 84
rutsky Avatar answered Sep 27 '22 19:09

rutsky


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.

like image 43
Kaushal Avatar answered Sep 27 '22 18:09

Kaushal