Pymongo returns a cursor with it I am able to iterate over the results and append their documents to a list. Is there a way to get the result documents in a list directly? Thanks
The find method returns a PyMongo cursor. With the next method, we get the next document from the result set. The rewind method rewinds the cursor to its unevaluated state. With the list method, we can transform the cursor to a Python list.
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.
As we already discussed what is a cursor. It is basically a tool for iterating over MongoDB query result sets. This cursor instance is returned by the find() method.
The following code will convert the entire result set (Cursor
) into a list
:
myresults = list(mydb.mycollection.find())
This is fine for relatively small result sets, as you are pulling everything into memory.
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