Python MongoDB aggregation ORM
Project description
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
Response as list
By default aggregate returns cursor. If you want it to return a list of documents use as_list
argument:
cursor = pipeline.aggregate(as_list=True)
Changelog
1.0.2 (2020-09-01)
- Added
$addFields
and$set
stages. - Added
$filter
operator.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
mongo-aggregation-1.0.2.tar.gz
(11.6 kB
view hashes)