mongo_aggregation
Python MongoDB Aggregation ORM class.
Installation
pip install mongo_aggregation
Usage examples
import pymongo
from datetime import datetime
from dateutil.relativedelta import relativedelta
from mongo_aggregation import MongoAggregation
# Usual pymongo connection
client = pymongo.MongoClient('mongodb://localhost:27017/test')
db = client.get_database()
today = datetime.now()
yesterday = today - relativedelta(days=1)
# Compose the pipeline
pipeline = MongoAggregation(collection=db.action)
pipeline.match(
{'date': {'$gte': yesterday, '$lt': today}},
completed=True,
_cls={'$in': [
'Action.Order', 'Action.StorageIncome', 'Action.StorageCancellation', 'Action.StorageMovementOutcome'
]},
).smart_project(
'transactions.amount,_cls', '_id'
).append([
{'$project': {
'_cls': 1,
'date': 1,
'transactions.amount': 1,
'transactions.cashbox': 1,
}},
]).project(
{'transactions.amount': 1, 'transactions.cashbox': 1}, _cls=1, date=1
).project(
transactions=1, _cls=1, date=1
)
# Run it
cursor = pipeline.aggregate()
# Iterate over result
for doc in cursor:
print(doc)
break
Methods description
pipeline.sort('-doctor')
# {'$sort': {'doctor': -1}}
pipeline.sort({'doctor': 1})
# {'$sort': {'doctor': 1}}
pipeline.sort('doctor', '-patient')
# [{'$sort': {'doctor': 1}}, {'$sort': {'-patient': 1}}]
order_byis an alias tosort.
pipeline.order_by('-doctor')
# {'$sort': {'doctor': -1}}
pipeline.replace_root('doctor')
# {'$replaceRoot': {'newRoot': '$doctor'}}
Returns count. Does not add stage.
pipeline.count()
2
Response as list
By default aggregate returns cursor. If you want it to return a list of documents use as_list argument:
data = pipeline.aggregate(as_list=True)
Patterns module
Provides operators and some other patterns in python functions way.
Imports:
from mongo_aggregation.patterns import regex
and_({'a': True}, b=True, c=True)
# {'$and': [{'a': True}, {'b': True}, {'c': True}]}
or_({'a': True}, b=True, c=True)
# {'$or': [{'a': True}, {'b': True}, {'c': True}]}
regex('name', i=True)
# {'$regex': 'name', '$options': 'i'}
Aggregation patterns module
Provides aggregation operators and some other patterns in python functions way.
Imports:
from mongo_aggregation.aggr_patterns import merge_objects
- $ifNull
There are two variations:
if_null('$doctor', {})
{'$ifNull': ['$doctor', {}]}
ifNull('$doctor', '')
{'$ifNull': ['$doctor', '']}
Function looks after dollar prefix, so you can skip it:
if_null('doctor', {})
{'$ifNull': ['$doctor', {}]}
- $in
There are two variations:
in_('doctor', 'doctors')
{'$in': ['$doctor', '$doctors']}
merge_objects('$doctor', first_name='John', last_name='Doe')
# {'$mergeObjects': ['$doctor', {'first_name': 'John', 'last_name': 'Doe'}]}
Others
objfunction
Returns dictionary with specified fields as keys and values. For better understanding see usage examples below.
>>> obj('name,description')
{'name': '$name', 'description': '$description'}
>>> obj('name', 'description')
{'name': '$name', 'description': '$description'}
>>> obj('name,description', id='$code')
{'name': '$name', 'description': '$description', 'id': '$code'}
Changelog
1.0.10 (2021-01-19)
- Fixed bug with multiple operators for a field in a
_convert_names_with_underlines_to_dotspattern.
1.0.9 (2020-12-24)
- Added
in_aggregation pattern.
1.0.8 (2020-12-11)
- Added
and_,and_nor,and_ormethods toMongoMatchFilter.
1.0.7 (2020-09-19)
- Small fix.
1.0.6 (2020-11-19)
- Added
if_nullpattern. - Removed
get_countmethod.countnow returns count and does not addcountstage. - Added
objpattern.
1.0.5 (2020-09-25)
- Added
order_bymethod.
1.0.4 (2020-09-25)
- Bug fixes.
1.0.3 (2020-09-01)
.sortnow supports-emailsorting format (direction and field name by string).- Added
.replace_rootmethod. - Added
or_andand_logical operators._andis deprecated now. - Added
regexoperator pattern. - Added
merge_objectsaggregation operator (./aggr_patterns).
1.0.2 (2020-09-01)
- Added
$addFieldsand$setstages. - Added
$filteroperator.
Metadata
Release files for mongo-aggregation 1.0.12
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| mongo-aggregation-1.0.12.tar.gz | 14.5 kB | Without provenance | Details for mongo-aggregation-1.0.12.tar.gz |
Release files / mongo-aggregation-1.0.12.tar.gz
| Download URL | mongo-aggregation-1.0.12.tar.gz |
|---|---|
| Size | 14.5 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
0668de09437b33d1b67cbad5f8840370581089d82eb7e1bfaf82818de565f999
|
|
BLAKE2b-256 checksum How to use checksums |
44b585177389518d2c671838b88e4d13ceeaed3d644439d651e3ca97a66d2fb4
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/3.4.2 importlib_metadata/4.6.1 pkginfo/1.7.1 requests/2.26.0 requests-toolbelt/0.9.1 tqdm/4.61.2 CPython/3.9.16
|
Security for mongo-aggregation 1.0.12
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.