8000 Add support for $sortyCount aggregation command by userlerueda · Pull Request #896 · mongomock/mongomock · GitHub
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content

Add support for $sortyCount aggregation command #896

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

Open
wants to merge 5 commits into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 16 additions & 1 deletion mongomock/aggregate.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
import itertools
import math
import numbers
from typing import Dict, Union
from packaging import version
import random
import re
Expand Down Expand Up @@ -1362,6 +1363,20 @@ def _handle_sample_stage(in_collection, unused_database, options):
return shuffled[:size]


def _handle_sort_by_count_stage(in_collection, unused_database, options: Union[str, Dict]):
if isinstance(options, Dict):
raise NotImplementedError(
"Although a dictionary is a valid option for the $sortByCount stage, "
'it is currently not implemented in Mongomock.'
)
field_to_count = options.lstrip("$")

counter = collections.Counter(
[doc[field_to_count] for doc in in_collection if field_to_count in doc]
)
return [{"_id": key, "count": count} for key, count in counter.most_common()]


def _handle_sort_stage(in_collection, unused_database, options):
sort_array = reversed([{x: y} for x, y in options.items()])
sorted_collection = in_collection
Expand Down Expand Up @@ -1632,7 +1647,7 @@ def _handle_match_stage(in_collection, database, options):
'$set': _handle_add_fields_stage,
'$skip': lambda c, d, o: c[o:],
'$sort': _handle_sort_stage,
'$sortByCount': None,
'$sortByCount': _handle_sort_by_count_stage,
'$unset': None,
'$unwind': _handle_unwind_stage,
}
Expand Down
20 changes: 20 additions & 0 deletions tests/test__mongomock.py
Original file line number Diff line number Diff line change
Expand Up @@ -4218,6 +4218,26 @@ def test__aggregate_with_missing_fields1(self):
]
self.cmp.compare_ignore_order.aggregate(pipeline)

def test__aggregate_sort_by_count_1(self):
pipeline = [
{
"$facet": {
"pipeline_a": [{"$sortByCount": "$a"}],
}
}
]
self.cmp.compare.aggregate(pipeline)

def test__aggregate_sort_by_count_2(self):
pipeline = [
{
"$facet": {
"pipeline_b": [{"$sortByCount": "$b"}],
}
}
]
self.cmp.compare.aggregate(pipeline)

def test__group_with_missing_fields1(self):
self.cmp.do.delete_many({})

Expand Down
Loading
0