用法

  1. pipeline = []
  2. res = db.col.aggregate(pipeline) # 返回cursor
  3. res = model.objects.aggregate(pipeline)
  4. print(list(res))

$match

{ $match: { $expr: { } } }

  1. # 简单相等查询
  2. {'$match': {'name': 'zoro'}}
  3. # AND 查询
  4. {'$match': {'name': 'zoro', 'age': 20}}
  5. # OR 查询
  6. {'$match':
  7. {
  8. '$or': [
  9. { 'score': { '$gt': 70, '$lt': 90 } },
  10. { 'views': { '$gte': 1000 } }
  11. ]
  12. }
  13. }

$sort

{ $sort: { : , : … } }

  1. # 正序
  2. {'$sort': {'name': 1}}
  3. # 逆序
  4. {'$sort': {'name': -1}}
  5. # 多列
  6. {'$sort': {'name': 1, 'age': -1}}

$facet, $skip, $limit, $count

  1. {
  2. '$facet': {
  3. 'data': [{'$skip': (page - 1) * pageSize}, {'$limit': pageSize}],
  4. 'total': [
  5. {'$count': 'count'}
  6. ],
  7. }
  8. }

$group

  1. {
  2. '$group': {
  3. '_id': {'name': '$name', 'age': '$age'}
  4. }
  5. }

$match + $group + $sort + $facet

查询 + 去重 + 排序 + 分页

  1. pipeline = [
  2. {
  3. '$match': {'Species': 'NDM8'}
  4. },
  5. {
  6. '$group': {'_id': {'Species': '$Species', 'Map_ID': '$Map_ID'}}
  7. },
  8. {
  9. '$sort': {'_id.Map_ID': -1}
  10. },
  11. {
  12. '$facet': {
  13. 'data': [{'$skip': 20}, {'$limit': 10}],
  14. 'total': {'$count': 'count'}
  15. },
  16. }
  17. ]
  1. [
  2. {
  3. 'data': [
  4. {'_id': {'Species': 'NDM8', 'Map_ID': 'map00061'}},
  5. {'_id': {'Species': 'Pima90', 'Map_ID': 'map00061'}},
  6. {'_id': {'Species': 'Pima90', 'Map_ID': 'map00073'}}],
  7. 'total': [{'count': 512}]
  8. }
  9. ]

$unwind

将指定的Array列展开为多行

  1. {
  2. $unwind: '$fieldName',
  3. }