diff --git a/mongoengine/queryset/base.py b/mongoengine/queryset/base.py index 647eafc6..2c80218c 100644 --- a/mongoengine/queryset/base.py +++ b/mongoengine/queryset/base.py @@ -1198,6 +1198,10 @@ class BaseQuerySet(object): pipeline = initial_pipeline + list(pipeline) + if IS_PYMONGO_3 and self._read_preference is not None: + return self._collection.with_options(read_preference=self._read_preference) \ + .aggregate(pipeline, cursor={}, **kwargs) + return self._collection.aggregate(pipeline, cursor={}, **kwargs) # JS functionality diff --git a/tests/queryset/queryset.py b/tests/queryset/queryset.py index 9c7ac0e4..497a0d23 100644 --- a/tests/queryset/queryset.py +++ b/tests/queryset/queryset.py @@ -4438,6 +4438,26 @@ class QuerySetTest(unittest.TestCase): self.assertEqual(bars._cursor._Cursor__read_preference, ReadPreference.SECONDARY_PREFERRED) + @needs_mongodb_v26 + def test_read_preference_aggregation_framework(self): + class Bar(Document): + txt = StringField() + + meta = { + 'indexes': ['txt'] + } + # Aggregates with read_preference + bars = Bar.objects \ + .read_preference(ReadPreference.SECONDARY_PREFERRED) \ + .aggregate() + if IS_PYMONGO_3: + self.assertEqual(bars._CommandCursor__collection.read_preference, + ReadPreference.SECONDARY_PREFERRED) + else: + self.assertNotEqual(bars._CommandCursor__collection.read_preference, + ReadPreference.SECONDARY_PREFERRED) + + def test_json_simple(self): class Embedded(EmbeddedDocument):