From f7534b8fc22eb3fcb8cabc8ccef34e135e11d713 Mon Sep 17 00:00:00 2001 From: superqwer Date: Wed, 11 Mar 2020 08:52:43 +0300 Subject: [PATCH 1/2] project missing fields in dict --- mongomock/aggregate.py | 2 +- tests/test__collection_api.py | 11 +++++++++++ 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/mongomock/aggregate.py b/mongomock/aggregate.py index 12a6f62b81..6b874b466e 100644 --- a/mongomock/aggregate.py +++ b/mongomock/aggregate.py @@ -980,7 +980,7 @@ def _handle_project_stage(in_collection, unused_database, options): for in_doc, out_doc in zip(in_collection, new_fields_collection): try: - out_doc[field] = _parse_expression(value, in_doc) + out_doc[field] = _parse_expression(value, in_doc, ignore_missing_keys=True) except KeyError: pass if (method == 'include') == (include_id is not False and include_id is not 0): diff --git a/tests/test__collection_api.py b/tests/test__collection_api.py index 9b8293ac54..a98b1f145a 100644 --- a/tests/test__collection_api.py +++ b/tests/test__collection_api.py @@ -3068,6 +3068,17 @@ def test__aggregate_project_missing_fields(self): ]) self.assertEqual([{}], list(actual)) + def test__aggregate_project_missing_nested_fields(self): + self.db.collection.insert_one({'_id': 1, 'a': 2, 'b': {'c': 1}}) + actual = self.db.collection.aggregate([ + {'$match': {'_id': 1}}, + {'$project': collections.OrderedDict([ + ('_id', False), + ('nested_dictionary', {'c': '$b.c', 'd': '$b.d'}) + ])} + ]) + self.assertEqual([{'nested_dictionary': {'c': 1}}], list(actual)) + def test__aggregate_project_out(self): self.db.collection.insert_one({'_id': 1, 'arr': {'a': 2, 'b': 3}}) self.db.collection.insert_one({'_id': 2, 'arr': {'a': 4, 'b': 5}}) From 36aab188f74667642399c9da9eff8700a55872f5 Mon Sep 17 00:00:00 2001 From: superqwer Date: Wed, 11 Mar 2020 13:25:17 +0300 Subject: [PATCH 2/2] project missing fields in dict mongomock tests --- tests/test__mongomock.py | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/tests/test__mongomock.py b/tests/test__mongomock.py index 4e10c4c179..422ec7d300 100644 --- a/tests/test__mongomock.py +++ b/tests/test__mongomock.py @@ -2239,6 +2239,19 @@ def test__aggregate_project_with_subfields_exclude(self): ] self.cmp.compare_ignore_order.aggregate(pipeline) + def test_aggregate_project_with_missing_subfields(self): + self.cmp.do.insert_many([ + {'a': {'b': 3}, 'other': 1}, + {'a': {'b': {'c': 4}, 'd': 5}}, + {'a': {'c': 3, 'd': 5}}, + {'b': {'c': 3}}, + {'a': 5}, + ]) + pipeline = [ + {'$project': {'_id': False, 'e': '$a.b.c'}} + ] + self.cmp.compare_ignore_order.aggregate(pipeline) + def test__aggregate_unwind_project_id(self): self.cmp.do.insert_one({ '_id': 'id0',