Skip to content

Commit

Permalink
Fix aggregation failing if index does not exists, added test (#646)
Browse files Browse the repository at this point in the history
Co-authored-by: Daniil Volynkin <dvvolynkin@avito.ru>
  • Loading branch information
dvvolynkin and Daniil Volynkin committed Feb 6, 2022
1 parent 2826cac commit 93da9a9
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 3 deletions.
10 changes: 7 additions & 3 deletions mongomock/aggregate.py
Original file line number Diff line number Diff line change
Expand Up @@ -369,10 +369,14 @@ def _handle_project_operator(self, operator, values):
values = self.parse(values) if isinstance(values, str) else self.parse_many(values)
return _GROUPING_OPERATOR_MAP[operator](values)
if operator == '$arrayElemAt':
key, index = values
key, value = values
array = self._parse_basic_expression(key)
index = self.parse(index)
return array[index]
index = self.parse(value)
try:
return array[index]
except IndexError as error:
raise KeyError('Array have length less than index value') from error

raise NotImplementedError("Although '%s' is a valid project operator for the "
'aggregation pipeline, it is currently not implemented '
'in Mongomock.' % operator)
Expand Down
14 changes: 14 additions & 0 deletions tests/test__mongomock.py
Original file line number Diff line number Diff line change
Expand Up @@ -3189,6 +3189,20 @@ def test__aggregate_bug_473(self):
}},
])

def test__aggregate_array_eleme_at(self):
self.cmp.do.drop()
self.cmp.do.insert_many([
{'values_list': [1, 2]},
{'values_list': [1, 2, 3]},
])

self.cmp.compare.aggregate([{
'$project': {
'first_user_id': {'$arrayElemAt': ['$values_list', 2]},
'other_user_id': {'$arrayElemAt': ['$values_list', -1]},
},
}])

def test_aggregate_bug_607(self):
"""Regression test for bug https://github.com/mongomock/mongomock/issues/607."""
self.cmp.do.drop()
Expand Down

0 comments on commit 93da9a9

Please sign in to comment.