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.
The find_One() method of pymongo is used to retrieve a single document based on your query, in case of no matches this method returns nothing and if you doesn't use any query it returns the first document of the collection.
Check if the Cursor object is empty or not? Approach 1: The cursor returned is an iterable, thus we can convert it into a list. If the length of the list is zero (i.e. List is empty), this implies the cursor is empty as well.
insert_one() Method This method returns an instance of class “~pymongo. results. InsertOneResult” which has a “_id” field that holds the id of the inserted document. If the document does not specify an “_id” field, then MongoDB will add the “_id” field and assign a unique object id for the document before inserting.
To get all the Documents of the Collection use find() method. The find() method takes a query object as a parameter if we want to find all documents then pass none in the find() method.
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")})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With