简体   繁体   中英

PyMongo find_one() returns nothing when passed _id as query parameter

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.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM