Gerswin Lee
Gerswin Lee

Reputation: 1365

Search for a document by ObjectId in mongodb with pymongo

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?

Upvotes: 121

Views: 139879

Answers (3)

Rahul Khatoliya
Rahul Khatoliya

Reputation: 125

In case of custom id (for example : String), you can do :

collection.find_one("key")

Upvotes: 0

cottontail
cottontail

Reputation: 23449

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("667738abeb70e4ffb4731400"))

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).

Upvotes: 4

Evgenii
Evgenii

Reputation: 3448

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)})]

Upvotes: 251

Related Questions