'Mongoengine: create a QuerySet from a MongoDB cursor

Some part of the application I'm working in is expecting a mongoengine QuerySet.

I have a MongoDB cursor with the info I need, generated by an aggregation.

Since mongoengine documentation specifies that a QuerySet is a wrapper of a MongoDB cursor, is there any way to create a QuerySet with a given cursor?

Note: There is an obvious solution, querying the database again:

queryset = Model.objects.filter(_id__in=[r['_id'] for r in cursor])

But it's rather ugly. The ideal solution would be something like calling the constructor of QuerySet, since it is a wrapper of cursor. But constructor does not accept cursor as an argument.



Solution 1:[1]

QuerySet is nothing but just a list. So you can convert the output you get from aggregating into a list like below and directly use that list as QuerySet.

queryset = list(cursor)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Suraj Rao