Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make pymongo's find() return a list?

Tags:

pymongo

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

like image 353
user971956 Avatar asked Nov 03 '12 15:11

user971956


People also ask

What does find () return in PyMongo?

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.

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 is PyMongo cursor object?

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.


1 Answers

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.

like image 86
Brian Cajes Avatar answered Oct 17 '22 22:10

Brian Cajes