In Python, how to get a record from string of ObjectID?

6,027 views
Skip to first unread message

Daniel W

unread,
Jul 7, 2011, 1:04:48 AM7/7/11
to mongodb-user
In Python, is there a way to "ObjectID-ify" a string?
E.g.:

>>> db.NY.find_one()
{u'_id': ObjectId('4e0c16a5466754281b000000'), u'gotto': 13436829}

>>> db.NY.find({'_id' : '4e0c16a5466754281b000000'}).count()
0

I know that this works:

>>> foo=db.NY.find_one()

>>> db.NY.find({'_id' : foo['_id']}).count()
1

But I'm wondering if there's a way to locate a record using Pymongo if
all you have is the string of its ObjectID.

Thanks


Nat

unread,
Jul 7, 2011, 1:07:53 AM7/7/11
to mongod...@googlegroups.com

Daniel W

unread,
Jul 7, 2011, 1:21:08 AM7/7/11
to mongodb-user
doh. so simple. thanks

On Jul 7, 3:07 pm, Nat <nat.lu...@gmail.com> wrote:
> you can use objectid.http://api.mongodb.org/python/1.7/api/pymongo/objectid.html

Francisco Corrales Morales

unread,
Sep 26, 2013, 5:26:56 PM9/26/13
to mongod...@googlegroups.com
Hi,
I can't manage to make it work.

How did you do it?

Jorge Puente Sarrín

unread,
Sep 26, 2013, 5:37:55 PM9/26/13
to mongod...@googlegroups.com
Very easy:

>>> from bson import ObjectId
>>> string = '4e0c16a5466754281b000000'
>>> ObjectId(string)
ObjectId('4e0c16a5466754281b000000')


--
--
You received this message because you are subscribed to the Google
Groups "mongodb-user" group.
To post to this group, send email to mongod...@googlegroups.com
To unsubscribe from this group, send email to
mongodb-user...@googlegroups.com
See also the IRC channel -- freenode.net#mongodb
 
---
You received this message because you are subscribed to the Google Groups "mongodb-user" group.
To unsubscribe from this group and stop receiving emails from it, send an email to mongodb-user...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.



--
Jorge Puente Sarrín.

Francisco Corrales Morales

unread,
Sep 26, 2013, 5:45:25 PM9/26/13
to mongod...@googlegroups.com
thanks,
I do like this:


query = "{'_id': 'ObjectId('%s')'  }" % (str(  string_id  ))




You received this message because you are subscribed to a topic in the Google Groups "mongodb-user" group.
To unsubscribe from this topic, visit https://groups.google.com/d/topic/mongodb-user/JVo0obd3rEc/unsubscribe.
To unsubscribe from this group and all its topics, send an email to mongodb-user...@googlegroups.com.

For more options, visit https://groups.google.com/groups/opt_out.



--
Francisco Corrales Morales
ITCR - 200837354

Bernie Hackett

unread,
Sep 26, 2013, 6:02:16 PM9/26/13
to mongod...@googlegroups.com
query = {'_id': ObjectId(string_id)}

Reply all
Reply to author
Forward
0 new messages