Search code examples
cursorpymongo

Pymongo: How to rewind a CommandCursor


I have an aggreagte command docs = self.collection.aggregate(query)which returns a CommandCursor.

I would need to loop the CommandCursor twice, but unlike a usual cursor, the pymongo CommandCursor does not have a rewind or any similar method (Docs).

Do I have any chance to do that without converting the cursor to a dict?


Solution

  • rewind option in cursor object calls the db again for the same query. So its also not a good option.

    The best you can do is to convert the commandCursor object into list or tuple.

    docs = list(self.collection.aggregate(query))