Search for a document by ObjectId in mongodb with pymongo
Asked Answered
K

2

118

I need to search an ObjectId with python using pymongo but I always get an error.

import pymongo
from pymongo import MongoClient
from pymongo import ObjectId

gate = collection.find({'_id': ObjectId(modem["dis_imei"])})

Any ideas how to search?

Katabatic answered 18/4, 2013 at 3:14 Comment(2)
What is version of pymongo?Greeson
my version is pymongo==2.5Katabatic
G
246

I use pymongo 2.4.1.

from bson.objectid import ObjectId
[i for i in dbm.neo_nodes.find({"_id": ObjectId(obj_id_to_find)})]
Greeson answered 18/4, 2013 at 5:9 Comment(3)
I update pymongo to 2.5 - all working. Can you see error message and your code?Greeson
@GerswinLee notice the "from bson.objectid"? You'll get an import error trying to import it from pymongo in version 2.5 You need python-bson package. I'm not sure if that's installed with pymongo or not.Rheum
For me to get it to work, I had to turn obj_id_to_find into a string i.e. str(obj_id_to_find)Homophonous
E
0

Assuming each document has a unique ObjectId, we can directly search for it using find_one. An example would look like:

from bson import ObjectId
collection.find_one(ObjectId("1234ab567c890d111213efgh"))

Note that unlike collection.find({}) which returns a cursor (so has to be iterated over to get the actual document), the above call returns either dict (if there is a match) or None (if there is no match).

Espinoza answered 3/5 at 23:47 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.