A utility library that provides a MongoDB-like query language for querying python collections. It's mainly intended to parse objects structured as fundamental types in a similar fashion to what is produced by JSON or YAML parsers.
Example:
frommongoqueryimportQuery, QueryErrorrecords= [
{"a": 5, "b": 5, "c": None},
{"a": 3, "b": None, "c": 8},
{"a": None, "b": 3, "c": 9},
{"a": 1, "b": 2, "c": 3},
{"a": 2, "c": 5},
{"a": 3, "b": 2},
{"a": 4},
{"b": 2, "c": 4},
{"b": 2},
{"c": 6}
]
a_is_3=Query({"a": 3})
# match a single objectmatched=a_is_3.match(record[1])
assertmatchedmatched=a_is_3.match(record[0])
assertnotmatched# filter elementsfiltered=filter(
a_is_3.match,
records
)
assertfiltered== [records[1], records[5]]
# incorrect filters raise QueryErrortry:
matched=query({"$foo": 2}).match(record[1])
exceptQueryError:
pass# => "$foo" operator isn't supportedThe syntax of queries matches closely the one of MongoDB queries, and translates it to python using the following rules:
operators and field identifiers are expressed as strings. For instance, the following MongoDB query:
{memos: {$elemMatch: {memo: 'on time',by: 'billing'}}}Translates straightforwardly to the following Python dict:
{ "memos": { "$elemMatch": { "memo": 'on time', "by": 'billing' } } }regular expressions are expected to be expressed as string containing the MongoDB regular expression syntax. For instance:
{description: {$regex: /^S/m}}Translates to the following Python dict:
{"description": {"$regex": "/^S/m"}}the boolean, null syntax used in MongoDB follows the JavaScript syntax. It is expected the python equivalents are used. For instance:
{a: {$exists: true},b: null}Translates to the following Python dict:
{"a": {"$exists": True}, "b": None}
- There are a few features that are not supported by
mongoquery: - Only the
"/pattern/<options>"syntax is supported for$regex. As a consequence,$optionsisn't supported. $texthasn't been implemented.- Due to the pure python nature of this library,
$whereisn't supported. - The Geospatial operators
$geoIntersects,$geoWithin,$nearSphere, and$nearare not implemented. - Projection operators $`,
$elemMatch,$meta, and$sliceare not implemented (only querying is implemented) $typeis limited to recognising generic python types, it won't look into recognising the format of the data (for instance, it doesn't check Object ID's format, only that they are strings)
- Only the