Skip to content

weiliddat/mgqpy

Repository files navigation

mgqpy

codecov PyPI - Version

MongoDB query as a predicate function

This aims to be consistent with how MongoDB's matches documents. This includes traversal across nested dicts and lists, None and field-presence/absence handling.

Installation

pip install mgqpy

Usage

Test if an input satisfies a query.

Invalid queries (e.g. using $and without a list) will automatically return False.

Use the validate method to raise errors if there's a problem with the query.

from mgqpy import Query

predicate = Query({"foo.bar": {"$gt": 1}})

inputs = [
    {"foo": [{"bar": [1, 2]}]},
    {"foo": {"bar": 1}},
    {"foo": {"bar": 2}},
    {"foo": None},
]

filtered = filter(predicate.test, inputs)

assert list(filtered) == [
    {"foo": [{"bar": [1, 2]}]},
    {"foo": {"bar": 2}},
]

Use validate to validate queries given.

predicate = Query({"foo": {"$in": 1}})

try:
    predicate.validate()
except TypeError as e:
    # ...

validate returns the Query instance so you can chain test if you wish to validate and test against an input in one go.

input = {"foo": 1}

predicate.validate().test(input)

Supported operators

Comparison query operators

  • $eq
  • $eq (implicit), e.g. {"foo": None}
  • $ne
  • $gt
  • $gte
  • $lt
  • $lte
  • $in
  • $nin

Logical query operators

  • $and
  • $and (implicit), e.g. {"foo": 1, "bar": "baz"}
  • $or
  • $not
  • $nor

Evaluation query operators

  • $regex
  • $regex (implicit), e.g. {"foo": re.compile('^bar')}
  • $mod

Array query operators

  • $all
  • $elemMatch
  • $size

About

mongo query as a python predicate

Topics

Resources

License

Stars

Watchers

Forks

Languages