retrieve records by _id (hex representation)

66 views
Skip to first unread message

marc

unread,
Aug 5, 2009, 3:45:46 AM8/5/09
to mongodb-user
hi,

after creating a new record with pymongo i get an ObjectId() result.
is there a way to find a record with an url_encoded object id without
decoding the hex string before the lookup?

>>> db.test.remove({})
>>> res = db.test.insert({'name': 'mongo'})
>>> db.test.find({}).count()
1
>>> id = res['_id'].url_encode()
>>> id
'7f36794a4d4e12b105070000'
>>> db.test.find({'_id': id}).count()
0

the problem is, that i need the hex representation of an ID. my first
idea was to manually replace the _id field of every query like this
before doing the lookup:

>>> query = {'_id': '7f36794a4d4e12b105070000'}
>>> query['_id'] = ObjectId.url_decode(query['_id'])
>>> db.test.find(query).count()

but what happens to IDs that are not auto generated, for example the
email of an user as unique key? in my case i'm not able to figure out
if the supplied ID was auto generated or manually defined. is there a
way to do a lookup using the hex representation of the auto generated
ID?

thanks in advance,

cheers marc

marc

unread,
Aug 5, 2009, 8:56:13 AM8/5/09
to mongodb-user
okay, i found a solution.

thanks to mike and his very modular design of the pymongo driver. i've
overwritten the ObjectIdInjector to use the hex representation of the
ID, not the binary one. maybe this is a bit slower, but much more
easier to handle for me :)

from pymongo.connection import Connection
from pymongo.son_manipulator import SONManipulator
from pymongo.objectid import ObjectId

db_conn = Connection().test

class ObjectIdInjector(SONManipulator):
def transform_incoming(self, son, collection):
if not '_id' in son:
son['_id'] = ObjectId().url_encode()
return son
db_conn.add_son_manipulator(ObjectIdInjector())

db_conn.test.remove({})
id = db_conn.test.save({'a': 123})

print id

a = db_conn.test.find_one({})
b = db_conn.test.find_one({'_id': id})

assert a == b

Michael Dirolf

unread,
Aug 5, 2009, 9:04:13 AM8/5/09
to mongod...@googlegroups.com
cool - yeah that should work well.
Reply all
Reply to author
Forward
0 new messages