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
Asked
Active
Viewed 7.0k times
1 Answers
136
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.

mcont
- 1,749
- 1
- 22
- 33

Brian Cajes
- 3,274
- 3
- 21
- 22
-
1what if i have bigger results? what is recommended? – Jaziel_Inc Aug 25 '18 at 14:47
-
3@Jaziel_Inc if it's large then you can iterate over it e.g. `first_doc = next( mydb.mycollection.find() )`, where `first_doc` would be a dictionary – Alex Aug 28 '18 at 19:34
-
7For more rows: `c = mydb.mycollection.find(); first_5_rows = [next(c) for _ in range(5)]` – Alex Aug 28 '18 at 19:39
-
@AlexG thank you, so the other option is to iterate over the cursor. – Jaziel_Inc Aug 28 '18 at 21:31
-
1Thank you! Took too long to figure out that you can only iterate the Cursor once and need to convert it to a list otherwise! – Jonathan Brown Jan 26 '21 at 23:03