Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix aggregation failing if index does not exists #646

Merged
merged 1 commit into from
Feb 6, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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]
pcorpet marked this conversation as resolved.
Show resolved Hide resolved
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