PyMongo find_one() returns nothing when passed _id as query parameter
Solution 1
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")})
Solution 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.
SourMonk
Updated on July 09, 2022Comments
-
SourMonk almost 2 years
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-wrapping569bbe3a65193cde93ce7092
has made any difference.