Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 754
SourMonk Avatar asked Jan 17 '16 17:01

SourMonk


People also ask

What does find_One return PyMongo?

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.

How can I tell if PyMongo cursor is empty?

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.

What does Insert_one return PyMongo?

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.

How do I get all documents in PyMongo?

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.


1 Answers

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")})
like image 160
alecxe Avatar answered Nov 15 '22 07:11

alecxe