0

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())
2
  • 2
    print calls str on each argument, so print(ObjectId()) outputs the result of str(ObjectId()). You'll have to call repr (explicitly): print(repr(ObjectId())) Commented Apr 19, 2017 at 21:21
  • thanks - make sense. Commented Apr 19, 2017 at 21:44

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

Before of converting directly from str to objectid try you validate with ObjectId.is_valid if is a validate str for objectid return True so you can do something as like:

  if ObjectId(session['id']):
      try:
          id_object_valid = ObjectId(session['id'])
      except (InvalidId, TypeError):
          return False

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.