9

I have a single document in my Mongo database:

{"_id" : ObjectId("569bbe3a65193cde93ce7092"), 
 "categories" : [{_id: 0, "category": "Groceries"},
                 {_id: 1, "category": "Bills"}, . . .]}

Using PyMongo in my project, I get this result calling find_one():

x = db.collection.find_one({"_id": "ObjectId(\"569bbe3a65193cde93ce7092\")"})
print(x)
// None

Whenever I perform this same query in the Mongo shell, it returns my document. I cannot for the life of me figure out why this is not working. Using find({}) returns the document, so I know PyMongo can see it.

I can call find_one({"categories": {"$exists": True}}) to retrieve the document, and since this will be the only document containing "categories", this will work; however, now I'm just baffled as to why accessing the document by _id is giving me such trouble. Neither escaping the quotes nor quote-wrapping 569bbe3a65193cde93ce7092 has made any difference.

2 Answers 2

18

To add to the @Simulant answer, you need to import the ObjectId from the bson.objectid:

from bson.objectid import ObjectId

x = db.collection.find_one({"_id": ObjectId("569bbe3a65193cde93ce7092")})
4
  • Ah, I think this is what I was missing. Thanks!
    – SourMonk
    Jan 17, 2016 at 19:15
  • ObjectId is in the bson module. So it should be from bson import ObjectId
    – Sede
    Jan 17, 2016 at 21:00
  • @user3100115 not necessarily, see api.mongodb.org/python/1.7/api/pymongo/….
    – alecxe
    Jan 17, 2016 at 22:55
  • 1
    from pymongo.objectid import ObjectId -> ImportError: No module named objectid [3.5.1]
    – jtlz2
    Oct 30, 2017 at 11:40
2

pass it without the quotes on the content of _id you also need to import ObjectId.

from bson.objectid import ObjectId

{"_id": ObjectId("569bbe3a65193cde93ce7092")}

If you pass it with quotes you are searching for an Object with the String ObjectId("569bbe3a65193cde93ce7092") as ID. But in MongoDB the ID is an Object and not a String. Thats a difference.

1
  • I get 'ObjectId is undefined' if I remove the quotes
    – SourMonk
    Jan 17, 2016 at 17:57

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.