Commit cab4cfa7 by Peter Weidenbach

aggregation field operations added

parent b48e773b
from .gridfs import overwrite_file
from .aggregate import get_objects_and_count_of_occurrence
from .aggregate import get_objects_and_count_of_occurrence, get_field_average, get_field_sum, get_field_execute_operation
__all__ = [
'overwrite_file',
'get_objects_and_count_of_occurrence'
'get_objects_and_count_of_occurrence',
'get_field_average',
'get_field_sum',
'get_field_execute_operation'
]
......@@ -17,3 +17,23 @@ def get_objects_and_count_of_occurrence(collection, object_path, unwind=False, m
result = list(collection.aggregate(pipeline))
logging.debug(result)
return result
def get_field_sum(collection, object_path, match=None):
return get_field_execute_operation("$sum", collection, object_path, match=match)
def get_field_average(collection, object_path, match=None):
return get_field_execute_operation("$avg", collection, object_path, match=match)
def get_field_execute_operation(operation, collection, object_path, match=None):
pipeline = []
if match is not None:
pipeline.append({"$match": match})
pipeline.append({"$group": {"_id": "null", "total": {operation: object_path}}})
tmp = collection.aggregate(pipeline)
result = 0
for item in tmp:
result = item['total']
return result
from common_helper_mongo.aggregate import get_objects_and_count_of_occurrence
from common_helper_mongo.aggregate import get_objects_and_count_of_occurrence,\
get_field_sum, get_field_average
import unittest
from tests.base_class_database_test import MongoDbTest
......@@ -24,7 +25,16 @@ class TestAggregate(MongoDbTest):
result = get_objects_and_count_of_occurrence(self.test_collection, "$test_txt", unwind="False", match={"test_int": 0})
self.assertEqual(len(result), 1, "number of results not correct")
self.assertEqual(result[0]['_id'], "item 0")
print(result)
def test_get_field_sum(self):
self.add_simple_test_data()
result = get_field_sum(self.test_collection, "$test_int")
self.assertEqual(result, 45)
def test_get_field_avg(self):
self.add_simple_test_data()
result = get_field_average(self.test_collection, "$test_int")
self.assertEqual(result, 4.5)
if __name__ == "__main__":
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment