用法
pipeline = []res = db.col.aggregate(pipeline) # 返回cursorres = model.objects.aggregate(pipeline)print(list(res))
$match
{ $match: { $expr: {
} } }
# 简单相等查询{'$match': {'name': 'zoro'}}# AND 查询{'$match': {'name': 'zoro', 'age': 20}}# OR 查询{'$match':{'$or': [{ 'score': { '$gt': 70, '$lt': 90 } },{ 'views': { '$gte': 1000 } }]}}
$sort
{ $sort: {
: , : … } }
# 正序{'$sort': {'name': 1}}# 逆序{'$sort': {'name': -1}}# 多列{'$sort': {'name': 1, 'age': -1}}
$facet, $skip, $limit, $count
{'$facet': {'data': [{'$skip': (page - 1) * pageSize}, {'$limit': pageSize}],'total': [{'$count': 'count'}],}}
$group
{'$group': {'_id': {'name': '$name', 'age': '$age'}}}
$match + $group + $sort + $facet
查询 + 去重 + 排序 + 分页
pipeline = [{'$match': {'Species': 'NDM8'}},{'$group': {'_id': {'Species': '$Species', 'Map_ID': '$Map_ID'}}},{'$sort': {'_id.Map_ID': -1}},{'$facet': {'data': [{'$skip': 20}, {'$limit': 10}],'total': {'$count': 'count'}},}]
[{'data': [{'_id': {'Species': 'NDM8', 'Map_ID': 'map00061'}},{'_id': {'Species': 'Pima90', 'Map_ID': 'map00061'}},{'_id': {'Species': 'Pima90', 'Map_ID': 'map00073'}}],'total': [{'count': 512}]}]
$unwind
将指定的Array列展开为多行
{$unwind: '$fieldName',}
