Search code examples
pythonmongodbpymongobson

PyMongo: ObjectId() prints string instead of Object


I am trying to convert an id string to an ObjectId()

I have the following imports:

from pymongo import MongoClient
import pymongo
from bson.objectid import ObjectId

If i print:

print(ObjectId(session['id']))
print(ObjectId())

I get the following:

58a09f4255c205690833f9dd
58f7d1606cb710c54a14ae82

Expected:

ObjectId("58a09f4255c205690833f9dd")
ObjectId("58f7d1606cb710c54a14ae82")

FYI:

pymongo==3.4.0
bson==0.4.7

I have tried (with no luck):

import bson
print(bson.ObjectId(session['id']))
print(bson.ObjectId())

Solution

  • You are already converting converting your id string to ObjectId indeed. As print function returns your ObjectId to string type in order to print properly, instead of printing the value itself, try printing the type.

    var1 = ObjectId(session['id'])
    var2 = ObjectId()
    
    print(var1)
    print(var2)
    print(type(var1))
    print(type(var2))
    

    Returns:

    58a09f4255c205690833f9dd
    58f7d1606cb710c54a14ae82
    <class 'bson.objectid.ObjectId'>
    <class 'bson.objectid.ObjectId'>
    

    So you can use var1 and var2 in where you want to use your ObjectIds.