上个星期,主要写了收入相关的接口测试;统计收入的过程中,需要用到MongoDB的聚合查询;目前做个简单的总结:
聚合操作处理数据记录,并返回计算值;MongoDB提供了3种方法执行聚合:the aggregation pipeline, the map-reduce function, 和单一目的的聚合方法(db.collection.count()和db.collection.distinct())。
这里主要介绍the aggregation pipeline: aggregate(pipeline, **kwargs)
1. 位置参数 pipeline,是一个数组列表list,具体的操作字段可参见官方文档stage-operators,例如:
1 2 3 4 5 6 7 8 |
match = {'$match': {"loanStatus": 2, "payInfo.type": 2, "payInfo.cashflow.0.status": 1, "items.0.type": {"$in": [1, 4]}, "confirmTime": {"$gte": -28800000}}} unwind = {'$unwind': "$payInfo.cashflow"} group = {'$group': {'total': {'$sum': '$payInfo.cashflow.realFee'}, 'count': {'$sum': 1}}} query_pipeline = [match, unwind, group] result = devDBMongo.get_aggregate(collection_name, query_pipeline) |
2. 关键字参数 **kwargs,具体使用参数参考官方文档pymongo.collection.Collection.aggregate,
3.返回值的类型是CommandCursor,是一个可迭代访问的类型,可转换为list类型 list(result),通过下标访问数据。