Ejemplo n.º 1
0
    def test_regex(self):
        for regex_instance in (
                re.compile("a*b", re.IGNORECASE),
                Regex("a*b", re.IGNORECASE)):
            res = self.round_tripped({"r": regex_instance})["r"]

            self.assertEqual("a*b", res.pattern)
            res = self.round_tripped({"r": Regex("a*b", re.IGNORECASE)})["r"]
            self.assertEqual("a*b", res.pattern)
            self.assertEqual(re.IGNORECASE, res.flags)

        unicode_options = re.I|re.M|re.S|re.U|re.X
        regex = re.compile("a*b", unicode_options)
        res = self.round_tripped({"r": regex})["r"]
        self.assertEqual(unicode_options, res.flags)

        # Some tools may not add $options if no flags are set.
        res = json_util.loads('{"r": {"$regex": "a*b"}}')['r']
        self.assertEqual(0, res.flags)

        self.assertEqual(
            Regex('.*', 'ilm'),
            json_util.loads(
                '{"r": {"$regex": ".*", "$options": "ilm"}}')['r'])

        # Check order.
        self.assertEqual(
            '{"$regex": ".*", "$options": "mx"}',
            json_util.dumps(Regex('.*', re.M | re.X)))

        self.assertEqual(
            '{"$regex": ".*", "$options": "mx"}',
            json_util.dumps(re.compile(b'.*', re.M | re.X)))
Ejemplo n.º 2
0
    def get(self, id=None):

        if id is None:
            parser = reqparse.RequestParser()
            parser.add_argument('figure', type=str, required=False)
            parser.add_argument('issue', type=str, required=False)
            parser.add_argument('filters', type=int, required=True)
            args = parser.parse_args()

            # Check filters
            if args.filters is 1: # Add filters
                # Check which filter to apply
                figure_list = [Regex.from_native(re.compile(str(i).replace("\"", "")+'.*')) for i in args.figure.split(',') if len(i) > 2]
                for t in figure_list:
                    t.flags ^= re.UNICODE
                issue_list = [Regex.from_native(re.compile(str(i).replace("\"", "")+'.*')) for i in args.issue.split(',') if len(i) > 2]
                for i in issue_list:
                    i.flags ^= re.UNICODE

                s = create_dic(mongo.db.directory.find({
                    "$or": [
                        {"figure": {"$in": figure_list}},
                        {"federal_entity": {"$in": issue_list}}
                    ]
                }))
            else:
                s = create_dic(mongo.db.directory.find({}))
        else:
            s = create_dic(mongo.db.directory.find({}))

        return jsonify(directory=s)
Ejemplo n.º 3
0
    def test_regex(self):
        for regex_instance in (re.compile("a*b", re.IGNORECASE),
                               Regex("a*b", re.IGNORECASE)):
            res = self.round_tripped({"r": regex_instance})["r"]

            self.assertEqual("a*b", res.pattern)
            res = self.round_tripped({"r": Regex("a*b", re.IGNORECASE)})["r"]
            self.assertEqual("a*b", res.pattern)
            self.assertEqual(re.IGNORECASE, res.flags)

        unicode_options = re.I | re.M | re.S | re.U | re.X
        regex = re.compile("a*b", unicode_options)
        res = self.round_tripped({"r": regex})["r"]
        self.assertEqual(unicode_options, res.flags)

        # Some tools may not add $options if no flags are set.
        # https://jira.mongodb.org/browse/CDRIVER-3773
        self.assertRaises(ValueError, bsonjs_loads, '{"r": {"$regex": '
                          '"a*b"}}')

        self.assertEqual(
            Regex(".*", "ilm"),
            bsonjs_loads('{"r": {"$regex": ".*", "$options": "ilm"}}')['r'])

        # Order should be $regex then $options
        self.assertEqual(
            '{ "regex" : { "$regex" : ".*", "$options" : "mx" } }',
            bsonjs_dumps({"regex": Regex(".*", re.M | re.X)}))

        self.assertEqual(
            '{ "regex" : { "$regex" : ".*", "$options" : "mx" } }',
            bsonjs_dumps({"regex": re.compile(b".*", re.M | re.X)}))
Ejemplo n.º 4
0
    def test_regex(self):
        for regex_instance in (
                re.compile("a*b", re.IGNORECASE),
                Regex("a*b", re.IGNORECASE)):
            res = self.round_tripped({"r": regex_instance})["r"]

            self.assertEqual("a*b", res.pattern)
            res = self.round_tripped({"r": Regex("a*b", re.IGNORECASE)})["r"]
            self.assertEqual("a*b", res.pattern)
            self.assertEqual(re.IGNORECASE, res.flags)

        unicode_options = re.I | re.M | re.S | re.U | re.X
        regex = re.compile("a*b", unicode_options)
        res = self.round_tripped({"r": regex})["r"]
        self.assertEqual(unicode_options, res.flags)

        # Some tools may not add $options if no flags are set.
        res = bsonjs_loads('{"r": {"$regex": "a*b"}}')['r']
        self.assertEqual(0, res.flags)

        self.assertEqual(
            Regex(".*", "ilm"),
            bsonjs_loads(
                '{"r": {"$regex": ".*", "$options": "ilm"}}')['r'])

        # Order should be $regex then $options
        self.assertEqual(
            '{ "regex" : { "$regex" : ".*", "$options" : "mx" } }',
            bsonjs_dumps({"regex": Regex(".*", re.M | re.X)}))

        self.assertEqual(
            '{ "regex" : { "$regex" : ".*", "$options" : "mx" } }',
            bsonjs_dumps({"regex": re.compile(b".*", re.M | re.X)}))
Ejemplo n.º 5
0
    def get(self):
        parser = reqparse.RequestParser()
        parser.add_argument('group', type=str, required=False)
        parser.add_argument('type', type=str, required=False)
        parser.add_argument('issue', type=str, required=False)
        parser.add_argument('filters', type=int, required=True)
        parser.add_argument('page', type=int, required=True)

        args = parser.parse_args()

        # Check filters
        if args.filters is 1: # Add filters
            # Check which filter to apply
            type_list = [Regex.from_native(re.compile(str(i).replace("\"", "")+'.*')) for i in args.type.split(',') if len(i) > 2]
            for t in type_list:
                t.flags ^= re.UNICODE
            group_list = [Regex.from_native(re.compile(str(i).replace("\"", "")+'.*')) for i in args.group.split(',') if len(i) > 2]
            for g in group_list:
                g.flags ^= re.UNICODE
            issue_list = [Regex.from_native(re.compile(str(i).replace("\"", "")+'.*')) for i in args.issue.split(',') if len(i) > 2]
            for i in issue_list:
                i.flags ^= re.UNICODE

            s = create_dic(mongo.db.organizations.find({
                "$or": [
                    {"social_group": {"$in": group_list}},
                    {"type": {"$in": type_list}},
                    {"geo_issue": {"$in": issue_list}}
                ]
            }).skip(args.page * 25).limit(25))
        else:
            s = create_dic(mongo.db.organizations.find({}).skip(args.page * 25).limit(25))

        return jsonify(organizations=s)
Ejemplo n.º 6
0
def _get_regex(data, position, as_class, tz_aware, uuid_subtype, compile_re):
    pattern, position = _get_c_string(data, position)
    bson_flags, position = _get_c_string(data, position)
    bson_re = Regex(pattern, bson_flags)
    if compile_re:
        return bson_re.compile(), position
    else:
        return bson_re, position
Ejemplo n.º 7
0
def _get_regex(data, position, as_class, tz_aware, uuid_subtype, compile_re):
    pattern, position = _get_c_string(data, position)
    bson_flags, position = _get_c_string(data, position)
    bson_re = Regex(pattern, bson_flags)
    if compile_re:
        return bson_re.try_compile(), position
    else:
        return bson_re, position
Ejemplo n.º 8
0
def test_sort_12(monty_sort, mongo_sort):
    docs = [{"a": Regex("^a")}, {"a": Regex("^b")}]
    sort = [("a", -1)]

    monty_c = monty_sort(docs, sort)
    mongo_c = mongo_sort(docs, sort)

    for i in range(len(docs)):
        assert next(mongo_c)["_id"] == next(monty_c)["_id"]
Ejemplo n.º 9
0
def search_artists():
    params = {item[0]: item[1] for item in request.forms.items() if item[1]}
    if int(params.pop('name_search_condition')) and 'name' in params:
        params['name'] = Regex(params['name'])
    if int(params.pop('alias_search_condition')) and 'aliases.name' in params:
        params['aliases.name'] = Regex(params['aliases.name'])
    results = collection.find(params, {
        '_id': 0,
        'name': 1,
        'aliases.name': 1,
        'rating.value': 1
    }).sort([('rating.value', -1)]).limit(50) if params else []
    return results
Ejemplo n.º 10
0
def test_qop_nin_10(monty_find, mongo_find):
    docs = [
        {
            "a": [Regex("*")]
        },
    ]
    spec = {"a": {"$nin": [[Regex("*")]]}}

    monty_c = monty_find(docs, spec)
    mongo_c = mongo_find(docs, spec)

    assert mongo_c.count() == 0
    assert monty_c.count() == mongo_c.count()
Ejemplo n.º 11
0
def test_qop_lt_28(monty_find, mongo_find):
    regex_0 = Regex("^0")
    regex_a = Regex("^a")
    docs = [
        {"a": regex_0},
    ]
    spec = {"a": {"$lt": regex_a}}

    monty_c = monty_find(docs, spec)

    # Can't have RegEx as arg to predicate
    with pytest.raises(OperationFailure):
        next(monty_c)
Ejemplo n.º 12
0
def object_hook(dct, json_options=DEFAULT_JSON_OPTIONS):
    if "$oid" in dct:
        return ObjectId(str(dct["$oid"]))
    if "$ref" in dct:
        return DBRef(dct["$ref"], dct["$id"], dct.get("$db", None))
    if "$date" in dct:
        return _get_date(dct, json_options)
    if "$regex" in dct:
        flags = 0
        # PyMongo always adds $options but some other tools may not.
        for opt in dct.get("$options", ""):
            flags |= _RE_OPT_TABLE.get(opt, 0)
        return Regex(dct["$regex"], flags)
    if "$minKey" in dct:
        return MinKey()
    if "$maxKey" in dct:
        return MaxKey()
    if "$binary" in dct:
        return _get_binary(dct, json_options)
    if "$code" in dct:
        return Code(dct["$code"], dct.get("$scope"))
    if "$uuid" in dct:
        return uuid.UUID(dct["$uuid"])
    if "$undefined" in dct:
        return None
    if "$numberLong" in dct:
        return Int64(dct["$numberLong"])
    if "$timestamp" in dct:
        tsp = dct["$timestamp"]
        return Timestamp(tsp["t"], tsp["i"])
    if "$numberDecimal" in dct:
        return Decimal128(dct["$numberDecimal"])
    return dct
Ejemplo n.º 13
0
    async def test_command_with_regex(self, test_db):
        await test_db.test.insert_one({'r': re.compile('.*')})
        await test_db.test.insert_one({'r': Regex('.*')})

        result = await test_db.command('aggregate', 'test', pipeline=[])
        for doc in result['result']:
            assert isinstance(doc['r'], Regex)
Ejemplo n.º 14
0
 def salesReportByCountry(self, year):
     from bson.regex import Regex
     pattern = '^' + str(year)
     regex = Regex(pattern)
     query = dict({'dateOfPurchase': {'$regex': regex}})
     proj = dict({
         'dateOfPurchase': 1,
         'extendedPrice': 1,
         'country': 1,
         '_id': 0
     })
     order = [('country', 1), ('dateOfPurchase', 1)]
     results = {}
     ## put results from generic fetch into nested dictionaries
     for doc in self.genericFetch(query, proj, order):
         country = doc['country']
         dop = doc['dateOfPurchase']
         month = str(dop[5:7])
         if country in results:
             temp = results[country]
             if month in temp:
                 price = temp[month] + doc['extendedPrice']
             else:
                 price = doc['extendedPrice']
             temp.update({month: price})
         else:
             results.update({country: {month: doc['extendedPrice']}})
     return results
Ejemplo n.º 15
0
    def find_by_primary_key(self, *kwargs):

        args = {}
        for idx, pk in enumerate(self.__document.pk_fields):
            if pk == "id":
                args["_id"] = kwargs[idx]
            elif pk == 'company_key':
                company_key_is_list = type(kwargs[idx]) is list
                if company_key_is_list:
                    args[pk] = {'$in': kwargs[idx]}
                else:
                    args[pk] = kwargs[idx]
            else:
                is_case_insensitive_pk = 'insensitive_pk_fields' in self.__document._meta and pk in self.__document._meta['insensitive_pk_fields']
                if not is_case_insensitive_pk:
                    args[pk] = kwargs[idx]
                else:
                    regex = Regex.from_native(re.compile("^" + kwargs[idx] + "$", re.IGNORECASE))
                    query_insensitive = {"$regex": regex}
                    args[pk] = query_insensitive
        doc = self.__document.collection.find(args).limit(1)
        try:
            doc = doc[0]
            return doc
        except IndexError:
            raise DocumentNotFound("{} not found".format(self.__document.collection_name))
Ejemplo n.º 16
0
def object_hook(dct, compile_re=True):
    if "$oid" in dct:
        return ObjectId(str(dct["$oid"]))
    if "$ref" in dct:
        return DBRef(dct["$ref"], dct["$id"], dct.get("$db", None))
    if "$date" in dct:
        secs = float(dct["$date"]) / 1000.0
        return EPOCH_AWARE + datetime.timedelta(seconds=secs)
    if "$regex" in dct:
        flags = 0
        # PyMongo always adds $options but some other tools may not.
        for opt in dct.get("$options", ""):
            flags |= _RE_OPT_TABLE.get(opt, 0)

        if compile_re:
            return re.compile(dct["$regex"], flags)
        else:
            return Regex(dct["$regex"], flags)
    if "$minKey" in dct:
        return MinKey()
    if "$maxKey" in dct:
        return MaxKey()
    if "$binary" in dct:
        if isinstance(dct["$type"], int):
            dct["$type"] = "%02x" % dct["$type"]
        subtype = int(dct["$type"], 16)
        if subtype >= 0xffffff80:  # Handle mongoexport values
            subtype = int(dct["$type"][6:], 16)
        return Binary(base64.b64decode(dct["$binary"].encode()), subtype)
    if "$code" in dct:
        return Code(dct["$code"], dct.get("$scope"))
    if bson.has_uuid() and "$uuid" in dct:
        return bson.uuid.UUID(dct["$uuid"])
    return dct
Ejemplo n.º 17
0
def search(prefix: str, mongo_client: MongoClient, collection_name: str) -> Cursor:
    if mongo_client is not None:
        regex: Regex = Regex('^{}'.format(prefix))
        
        return mongo_client[DB_NAME][collection_name].find({DATA_FIELD: {"$regex" : regex}}, {DATA_FIELD: 1, ID_FIELD: 0})
    else:
        raise IOError("Failed to connect to the DB.")
Ejemplo n.º 18
0
 def delete_by_prefix(self, collection_name, field, prefix):
     try:
         pattern = re.compile('^' + prefix + '.*')
         regex = Regex.from_native(pattern)
         regex.flags ^= re.IGNORECASE
         self.db[collection_name].delete_many({field: {'$regex': regex}})
     except Exception, e:
         raise e
Ejemplo n.º 19
0
 def query_nstart(self, value):
     # DOESN'T START WITH
     if isinstance(value, list):
         value = value[0]
     return MongoQuery(
         {self.field: {
             '$not': Regex('^' + value + '.*', 'i')
         }})
Ejemplo n.º 20
0
 def query_nend(self, value):
     # DOESN'T END WITH
     if isinstance(value, list):
         value = value[0]
     return MongoQuery(
         {self.field: {
             '$not': Regex('*.' + value + '$', 'i')
         }})
Ejemplo n.º 21
0
def test_validate_regex_valid_regex():
    class MyModel(Model):
        field: Regex

    regex = Regex("^.*$")
    instance = MyModel(field=regex)
    assert isinstance(instance.field, Regex)
    assert instance.field == regex
Ejemplo n.º 22
0
def _get_regex(
    data: Any, view: Any, position: int, dummy0: Any, opts: CodecOptions, dummy1: Any
) -> Tuple[Regex, int]:
    """Decode a BSON regex to bson.regex.Regex or a python pattern object."""
    pattern, position = _get_c_string(data, view, position, opts)
    bson_flags, position = _get_c_string(data, view, position, opts)
    bson_re = Regex(pattern, bson_flags)
    return bson_re, position
Ejemplo n.º 23
0
 def query_nlike(self, value):
     # WILDCARD NOT CONTAINS
     if isinstance(value, list):
         value = value[0]
     return MongoQuery(
         {self.field: {
             '$not': Regex('.*' + value + '.*', 'i')
         }})
Ejemplo n.º 24
0
def bbc_articles():

    # TODO consider adding more query parameters
    title = request.args.get('title', '')
    tag = request.args.get('tag', '')
    scraped_date = get_scraped_date(request)

    items = collection.find({
        "$and": [{
            'title': Regex(title)
        }, {
            'tag': Regex(tag)
        }, {
            'scraped_date': scraped_date
        }]
    })
    return dumps(items)
Ejemplo n.º 25
0
 def constructHashtags(self, keywords):
     hashtags_list = []
     for word in keywords:
         pattern = re.compile(word[1:], re.IGNORECASE)
         regex = Regex.from_native(pattern)
         regex.flags ^= re.UNICODE
         hashtags_list.append(regex)
     return hashtags_list
Ejemplo n.º 26
0
def _parse_canonical_regex(doc):
    """Decode a JSON regex to bson.regex.Regex."""
    regex = doc['$regularExpression']
    if len(doc) != 1:
        raise TypeError('Bad $regularExpression, extra field(s): %s' % (doc, ))
    if len(regex) != 2:
        raise TypeError('Bad $regularExpression must include only "pattern"'
                        'and "options" components: %s' % (doc, ))
    return Regex(regex['pattern'], regex['options'])
Ejemplo n.º 27
0
def test_qop_type_11(monty_find, mongo_find):
    docs = [{"a": Regex("^a")}, {"a": re.compile("^a")}]
    spec = {"a": {"$type": 11}}  # regex

    monty_c = monty_find(docs, spec)
    mongo_c = mongo_find(docs, spec)

    assert mongo_c.count() == 2
    assert monty_c.count() == mongo_c.count()
    def test_command_with_regex(self):
        db = self.client.pymongo_test
        db.test.drop()
        db.test.insert_one({'r': re.compile('.*')})
        db.test.insert_one({'r': Regex('.*')})

        result = db.command('aggregate', 'test', pipeline=[])
        for doc in result['result']:
            self.assertTrue(isinstance(doc['r'], Regex))
Ejemplo n.º 29
0
def test_sort_19(monty_sort, mongo_sort):
    docs = [
        {"a": ["x", True]},
        {"a": None},
        {"a": []},
        {"a": [5, []]},
        {"a": {"s": 7}},
        {"a": {"s": [9]}},
        {"a": {"s": 10}},
        {"a": 6},
        {"a": 4},
        {"a": [5, None]},
        {"a": [5, [1]]},
        {"a": [Decimal128("4.5"), Binary(b"0")]},
        {"a": [{"s": 5}, False]},
        {"a": [{"s": 9}]},
        {"a": [True, "y"]},
        {"a": Binary(b"a")},
        {"a": b"bytes"},
        {"a": ["abc"]},
        {"a": "banana"},
        {"a": "appple"},
        {"a": [Regex("^a", "ix")]},
        {"a": Regex("^b")},
        {"a": Code("x", {"m": 0})},
        {"a": Code("y")},
        {"a": Code("y", {})},
        {"a": Code("y", {"m": 0})},
        {"a": MinKey()},
        {"a": MaxKey()},
        {"a": Timestamp(0, 1)},
        {"a": Timestamp(1, 1)},
        {"a": ObjectId(b"000000000000")},
        {"a": ObjectId(b"000000000001")},
        {"a": datetime(1900, 1, 1)},
        {"a": datetime(1900, 1, 2)},
    ]
    sort = [("a", 1)]

    monty_c = monty_sort(docs, sort)
    mongo_c = mongo_sort(docs, sort)

    for i in range(len(docs)):
        assert next(mongo_c)["_id"] == next(monty_c)["_id"]
Ejemplo n.º 30
0
def test_validate_pattern_valid_bson_regex():
    class MyModel(Model):
        field: Pattern

    value = Regex("^.*$", flags="im")
    flags_int_value = re.compile("", flags=re.I | re.M).flags
    instance = MyModel(field=value)
    assert isinstance(instance.field, Pattern)
    assert instance.field.pattern == value.pattern
    assert instance.field.flags == flags_int_value
Ejemplo n.º 31
0
def _parse_legacy_regex(doc):
    pattern = doc["$regex"]
    # Check if this is the $regex query operator.
    if isinstance(pattern, Regex):
        return doc
    flags = 0
    # PyMongo always adds $options but some other tools may not.
    for opt in doc.get("$options", ""):
        flags |= _RE_OPT_TABLE.get(opt, 0)
    return Regex(pattern, flags)
Ejemplo n.º 32
0
    def like(field, value):
        escaped_value = re.escape(value.replace('%', ''))
        if value.startswith('%') and value.endswith('%'):
            value = re.compile('.*' + escaped_value + '.*', re.IGNORECASE)
        elif value.startswith('%'):
            value = re.compile(escaped_value + '$', re.IGNORECASE)
        elif value.endswith('%'):
            value = re.compile('^' + escaped_value, re.IGNORECASE)

        return {field: {'$regex': Regex.from_native(value)}}
Ejemplo n.º 33
0
    def get_ist_item(self, path=",Whole Program,", starting=False, ending=True):
        if type(path) is not list:
            path = [path]

        patterns = []
        for p in path:
            patterns.append(("^" if starting else "") + p + ("$" if ending else ""))

        pattern = re.compile("|".join(patterns))
        regex = Regex.from_native(pattern)
        regex.flags ^= re.UNICODE
        return self.ist.find({ "_id": regex })
Ejemplo n.º 34
0
    def get_list_of_nodes(self, sorting_order=None, name_filter=None, pagination=None):
        sort_direction = ASCENDING
        filter_object = {}
        skip_count = 0
        skip_limit = 0

        if sorting_order:
            if sorting_order['name'].lower() == 'asc':
                sort_direction = ASCENDING
            elif sorting_order['name'].lower() == 'desc':
                sort_direction = DESCENDING
        if name_filter:
            name_pattern = Regex.from_native(re.compile('^' + name_filter['name']))
            filter_object = {'name': name_pattern}
        if pagination:
            skip_count = int(pagination['skip'])
            skip_limit = int(pagination['limit'])

        return list(
            self.computation_nodes_collection.find(filter_object,
                                                   {'name': True, 'address': True, 'port': True, '_id': False},
                                                   sort=[('name', sort_direction)], skip=skip_count, limit=skip_limit))
Ejemplo n.º 35
0
    def calculate_sum_of_expenditure_types(self, query_params):

        # Build match pipeline
        match = {
            "$match": {}
        }

        if query_params['tipPodataka'] != []:
            match['$match']["tipPodataka.slug"] = {'$in': query_params['tipPodataka']}

        if "klasifikacija" in query_params:
            if query_params['klasifikacija']['broj'] != []:
                query_params['klasifikacija']['broj'] = [str(i) for i in query_params['klasifikacija']['broj']]

        if "filteri" in query_params:

            ### Let's set the values rage for ukupno ###
            if "ukupno" in query_params["filteri"] and 'veceIliJednako' in query_params["filteri"]['ukupno']:
                if 'ukupno' not in match['$match']:
                    match['$match']["ukupno"] = {}
                match['$match']["ukupno"]["$gte"] = query_params["filteri"]["ukupno"]["veceIliJednako"]

            if "ukupno" in query_params["filteri"] and 'manjeIliJednako' in query_params["filteri"]['ukupno']:
                if 'ukupno' not in match['$match']:
                    match['$match']["ukupno"] = {}
                match['$match']["ukupno"]["$lte"] = query_params["filteri"]["ukupno"]["manjeIliJednako"]

            ### Let's set the values rage for sopstveniPrihodi ###
            if "sopstveniPrihodi" in query_params["filteri"] and 'veceIliJednako' in query_params["filteri"]['sopstveniPrihodi']:
                if 'sopstveniPrihodi' not in match['$match']:
                    match['$match']["sopstveniPrihodi"] = {}
                match['$match']["sopstveniPrihodi"]["$gte"] = query_params["filteri"]["sopstveniPrihodi"]["veceIliJednako"]

            if "sopstveniPrihodi" in query_params["filteri"] and 'manjeIliJednako' in query_params["filteri"]['sopstveniPrihodi']:
                if 'sopstveniPrihodi' not in match['$match']:
                    match['$match']["sopstveniPrihodi"] = {}
                match['$match']["sopstveniPrihodi"]["$lte"] = query_params["filteri"]["sopstveniPrihodi"]["manjeIliJednako"]

            ### Let's set the values rage for prihodiBudzeta ###
            if "prihodiBudzeta" in query_params["filteri"] and 'veceIliJednako' in query_params["filteri"]['prihodiBudzeta']:
                if 'prihodiBudzeta' not in match['$match']:
                    match['$match']["prihodiBudzeta"] = {}
                match['$match']["prihodiBudzeta"]["$gte"] = query_params["filteri"]["prihodiBudzeta"]["veceIliJednako"]

            if "prihodiBudzeta" in query_params["filteri"] and 'manjeIliJednako' in query_params["filteri"]['prihodiBudzeta']:
                if 'prihodiBudzeta' not in match['$match']:
                    match['$match']["prihodiBudzeta"] = {}
                match['$match']["prihodiBudzeta"]["$lte"] = query_params["filteri"]["prihodiBudzeta"]["manjeIliJednako"]

            ### Let's set the values rage for donacije ###
            if "donacije" in query_params["filteri"] and 'veceIliJednako' in query_params["filteri"]['donacije']:
                if 'donacije' not in match['$match']:
                    match['$match']["donacije"] = {}
                match['$match']["donacije"]["$gte"] = query_params["filteri"]["donacije"]["veceIliJednako"]

            if "donacije" in query_params["filteri"] and 'manjeIliJednako' in query_params["filteri"]['donacije']:
                if 'donacije' not in match['$match']:
                    match['$match']["donacije"] = {}
                match['$match']["donacije"]["$lte"] = query_params["filteri"]["donacije"]["manjeIliJednako"]

            ### Let's set the values rage for ostali ###
            if "ostali" in query_params["filteri"] and 'veceIliJednako' in query_params["filteri"]['ostali']:
                if 'ostali' not in match['$match']:
                    match['$match']["ostali"] = {}
                match['$match']["ostali"]["$gte"] = query_params["filteri"]["ostali"]["veceIliJednako"]

            if "ostali" in query_params["filteri"] and 'manjeIliJednako' in query_params["filteri"]['ostali']:
                if 'ostali' not in match['$match']:
                    match['$match']["ostali"] = {}
                match['$match']["ostali"]["$lte"] = query_params["filteri"]["ostali"]["manjeIliJednako"]

        # Add other filters
        if query_params['godine'] != []:
            match['$match']["godina"] = {'$in': query_params['godine']}

        if "opstine" in query_params:
            if query_params['opstine'] != []:
                match['$match']["opstina.slug"] = {'$in': query_params['opstine']}

        # Build group pipeline
        group = {
            "$group": {
                "_id": {
                    "opstina": "$opstina.latinica",
                    "godina": "$godina",
                    "tipPodataka": "$tipPodataka.vrednost"
                },
                "prihodiBudzeta": {"$sum": "$prihodiBudzeta"},
                "sopstveniPrihodi": {"$sum": "$sopstveniPrihodi"},
                "donacije": {"$sum": "$donacije"},
                "ostali": {"$sum": "$ostali"},
                "ukupno": {"$sum": "$ukupno"}
            }
        }

        # Build project pipeline
        project = {
            "$project": {
                "_id": 0,
                "opstina": "$_id.opstina",
                "godina": "$_id.godina",
                "tipPodataka": "$_id.tipPodataka",
                "prihodiBudzeta": "$prihodiBudzeta",
                "sopstveniPrihodi": "$sopstveniPrihodi",
                "donacije": "$donacije",
                "ostali": "$ostali",
                "ukupno": "$ukupno",
            }
        }

        if "klasifikacija" in query_params:

            if query_params['klasifikacija']['broj'] != []:

                if 'pocinjeSa' in query_params['klasifikacija'] and query_params['klasifikacija']['pocinjeSa'] != '':

                    # Let's filter based on class options we picked and regex class number
                    match['$match']['$or'] = []
                    match_class_number = {"klasifikacija.broj": {'$in': query_params['klasifikacija']['broj']}}
                    match['$match']['$or'].append(match_class_number)


                    # Since Pymongo driver works with python regex logic, our pattern should be adopted in a way that python
                    # regex compiler understands, then convert it to a BSON Regex instance,
                    # read more: http://api.mongodb.org/python/current/api/bson/regex.html
                    pattern = re.compile("^%s" % query_params['klasifikacija']['pocinjeSa'])
                    regex = Regex.from_native(pattern)
                    regex.flags ^= re.UNICODE

                    # Build match pipeline
                    match_regex =  {
                        "klasifikacija.broj": regex
                    }

                    match['$match']['$or'].append(match_regex)
                else:
                    match['$match']["klasifikacija.broj"] = {'$in': query_params['klasifikacija']['broj']}

            else:
                if query_params['klasifikacija']['pocinjeSa'] != '':
                    pattern = re.compile("^%s" % query_params['klasifikacija']['pocinjeSa'])
                    regex = Regex.from_native(pattern)
                    regex.flags ^= re.UNICODE
                    # Build match pipeline
                    match['$match']["klasifikacija.broj"] = regex

            # Add this to param to group and project stages
            group['$group']['_id']['klasifikacijaBroj'] = "$klasifikacija.broj"
            project['$project']['klasifikacijaBroj'] = '$_id.klasifikacijaBroj'


        elif "kategorijaRoditelj" in query_params:
            if query_params['kategorijaRoditelj'] != []:
                match['$match']["kategorijaRoditelj.broj"] = {'$in': query_params['kategorijaRoditelj']}
            group['$group']['_id']['kategorijaRoditelj'] = "$kategorijaRoditelj.broj"
            project['$project']['kategorijaRoditelj'] = '$_id.kategorijaRoditelj'

        # Execute mongo request
        json_doc = mongo.db.opstine.aggregate([match, group, project])

        return json_doc['result']