mongo基础之 聚合命令 aggregation(4)

聚合操作介绍  

 db.collection.aggregate( [pipeline], <optional params> ) - performs an aggregation on a collection; returns a cursor
 2个参数,一个管道列表  一个可选参数

管道包括多个阶段

阶段描述
$addFields

向文档添加新字段。类似于 $project$addFields重塑流中的每个文档; 具体而言,通过向输出文档添加新字段,该文档包含输入文档和新添加字段中的现有字段。

格式 { $addFields: { <newField>: <expression>, ... } }
示例 db.scores.aggregate( [
   {
     $addFields: {
       totalHomework: { $sum: "$homework" } ,
       totalQuiz: { $sum: "$quiz" }
     }
   },
   {
     $addFields: { totalScore:
       { $add: [ "$totalHomework", "$totalQuiz", "$extraCredit" ] } }
   }
] )

expression 部分一般就是 公式 和 字段 ,字段一般用$column 表示。

$bucket

根据指定的表达式和存储区边界,将传入的文档分组,称为存储桶。

db.artwork.aggregate( [
  {
    $bucket: {
      groupBy: "$price",
      boundaries: [ 0, 200, 400 ],
      default: "Other",
      output: {
        "count": { $sum: 1 },
        "titles" : { $push: "$title" }
      }
    }
  }
] )
$bucketAuto

根据指定的表达式将传入的文档分类为特定数量的组(称为存储桶)。自动确定存储桶边界,以尝试将文档均匀地分配到指定数量的存储桶中。

db.artwork.aggregate( [
   {
     $bucketAuto: {
         groupBy: "$price",
         buckets: 4
     }
   }
] )
$collStats

返回有关集合或视图的统计信息。

包括读写时间个数,存储信息统计。

db.matrices.aggregate( [ { $collStats: { storageStats: { } } } ] )
$count返回聚合管道此阶段的文档数量计数。
db.scores.aggregate(
  [
    {
      $match: {
        score: {
          $gt: 80
        }
      }
    },
    {
      $count: "passing_scores"
    }
  ]
)

$count 后 跟字段名字,一共进来多少个文档

$facet

在同一组输入文档的单个阶段内处理多个聚合管道支持创建能够在单个阶段中跨多个维度或方面表征数据的多面聚合。

{ $facet:
   {
      <outputField1>: [ <stage1>, <stage2>, ... ],
      <outputField2>: [ <stage1>, <stage2>, ... ],
      ...

   }
}

db.artwork.aggregate( [
  {
    $facet: {
      "categorizedByTags": [
        { $unwind: "$tags" },
        { $sortByCount: "$tags" }
      ],
      "categorizedByPrice": [
        { $match: { price: { $exists: 1 } } },
        {
          $bucket: {
            groupBy: "$price",
            boundaries: [  0, 150, 200, 300, 400 ],
            default: "Other",
            output: {
              "count": { $sum: 1 },
              "titles": { $push: "$title" }
            }
          }
        }
      ],
      "categorizedByYears(Auto)": [
        {
          $bucketAuto: {
            groupBy: "$year",
            buckets: 4
          }
        }
      ]
    }
  }
])

$geoNear

基于与地理空间点的接近度返回有序的文档流。集成的功能 $match$sort以及$limit地理空间数据。输出文档包括附加距离字段,并且可以包括位置标识符字段。

{ $geoNear: { <geoNear options> } }
db.places.aggregate([
   {
     $geoNear: {
        near: { type: "Point", coordinates: [ -73.99279 , 40.719296 ] },
        key:"location",
        distanceField: "dist.calculated",
        maxDistance: 2,
        query: { category: "Parks" },
        includeLocs: "dist.location",
        spherical: true
     }
   }
])

$graphLookup

对集合执行递归搜索。对于每个输出文档,添加一个新的数组字段,其中包含该文档的递归搜索的遍历结果。

db.employees.aggregate( [
   {
      $graphLookup: {
         from: "employees",
         startWith: "$reportsTo",
         connectFromField: "reportsTo",
         connectToField: "name",
         as: "reportingHierarchy"
      }
   }
] )
$group

按指定的标识符表达式对文档进行分组,并将累加器表达式(如果已指定)应用于每个组。消耗所有输入文档,并为每个不同的组输出一个文档。输出文档仅包含标识符字段,如果指定,则包含累积字段。

{
  $group:
    {
      _id: <expression>, // Group By Expression
      <field1>: { <accumulator1> : <expression1> },
      ...
    }
 }
db.sales.aggregate(
  [
    // First Stage
    {
      $group :
        {
          _id : "$item",
          totalSaleAmount: { $sum: { $multiply: [ "$price", "$quantity" ] } }
        }
     },
     // Second Stage
     {
       $match: { "totalSaleAmount": { $gte: 100 } }
     }
   ]
 )
$indexStats

返回有关集合的每个索引的使用的统计信息。

db.orders.aggregate( [ { $indexStats: { } } ] )
$limit

将未修改的前n个文档传递给管道,其中n是指定的限制。对于每个输入文档,输出一个文档(对于前n个文档)或零文档(在前n个文档之后)。

db.article.aggregate(
    { $limit : 5 }
);
$listSessions

列出活动时间足以传播到system.sessions集合的所有会话。

db.system.sessions.aggregate( [ { $listSessions: { users: [ {user: "myAppReader", db: "test" } ] } } ] )
$lookup

同一数据库中的另一个集合执行左外连接,以 从“已连接”集合中过滤文档以进行处理。

表连接查询

{
  $lookup: {
    from: "otherCollection",
    as: "resultingArray",
    localField: "x",
    foreignField: "y"
  }
}
$match过滤文档流以仅允许匹配的文档未经修改地传递到下一个管道阶段。 $match使用标准的MongoDB查询。对于每个输入文档,输出一个文档(匹配)或零文档(不匹配)。
$out

将聚合管道的结果文档写入集合。要使用$out舞台,它必须是管道中的最后一个阶段。

db.books.aggregate( [
                      { $group : { _id : "$author", books: { $push: "$title" } } },
                      { $out : "authors" }
] )
$project

重新整形流中的每个文档,例如添加新字段或删除现有字段。对于每个输入文档,输出一个文档。

db.books.aggregate( [ { $project : { title : 1 , author : 1 } } ] )
$redact

access level 存取等级 有三种:
- $$DESCEND 返回当前等级的文档,排除掉该等级下的内嵌等级文档;
- $$PRUNE 排除掉满足条件的当前等级及其下属等级的所有内容,而不再检查其内嵌文档是否还有满足条件的内容;
- $$KEEP 保留满足条件的当前等级及其下属等级的所有内容,而不再检查其内嵌文档是否有满足条件的内容;

与其他完全过滤不同,$redact聚合是对文档内部进行操作,返回的是经过删减的文档,而不是将整个文档都删除掉。该操作符常常和$cond一起使用。

var userAccess = [ "STLW", "G" ];
db.forecasts.aggregate(
   [
     { $match: { year: 2014 } },
     { $redact: {
        $cond: {
           if: { $gt: [ { $size: { $setIntersection: [ "$tags", userAccess ] } }, 0 ] },
           then: "$$DESCEND",
           else: "$$PRUNE"
         }
       }
     }
   ]
);

$replaceRoot

用指定的嵌入文档替换文档。该操作将替换输入文档中的所有现有字段,包括_id字段。指定嵌入在输入文档中的文档以将嵌入文档提升到顶层。

db.people.aggregate( [
   { $replaceRoot: { newRoot: { $mergeObjects:  [ { dogs: 0, cats: 0, birds: 0, fish: 0 }, "$pets" ] }} }
] )

$sample

从输入中随机选择指定数量的文档。

db.users.aggregate(
   [ { $sample: { size: 3 } } ]
)

$skip

跳过前n个文档,其中n是指定的跳过编号,并将未修改的其余文档传递给管道。对于每个输入文档,输出零文档(对于前n个文档)或一个文档(如果在前n个文档之后)。

db.article.aggregate(
    { $skip : 5 }
);

$sort

按指定的排序键重新排序文档流。只有订单改变; 文件保持不变。对于每个输入文档,输出一个文档。

db.users.aggregate(
   [
     { $sort : { age : -1, posts: 1 } }
   ]
)

$sortByCount

根据指定表达式的值对传入文档进行分组,然后计算每个不同组中的文档计数。

db.exhibits.aggregate( [ { $unwind: "$tags" },  { $sortByCount: "$tags" } ] )
$unwind

从输入文档解构数组字段以输出每个元素的文档。每个输出文档都使用元素值替换数组。对于每个输入文档,输出n个文档,其中n是数组元素的数量,对于空数组,可以为零。

db.inventory2.aggregate( [
   { $unwind: { path: "$sizes", preserveNullAndEmptyArrays: true } }
] )

$set
修改或者添加新字段
db.animals.aggregate( [
  { $set: { "cats": 20 } }
] )
$unset

删除多个字段

db.books.aggregate([
   { $unset: [ "isbn", "copies" ] }
])
$replaceWith

删除多个字段

db.books.aggregate([
   { $unset: [ "isbn", "copies" ] }
])
$unset

删除多个字段

db.books.aggregate([
   { $unset: [ "isbn", "copies" ] }
])

db.aggregate()阶段

从3.6版开始,MongoDB还提供了以下 db.aggregate方法:

以下阶段使用db.aggregate()方法而不是db.collection.aggregate()方法。

阶段描述
$currentOp返回有关MongoDB部署的活动和/或休眠操作的信息。
$listLocalSessions列出最近在当前连接mongosmongod 实例上使用的所有活动会话。这些会话可能尚未传播到system.sessions集合中。

其他聚合操作符,参考 http://www.mongoing.com/docs/reference/operator/aggregation-pipeline.html

db.getCollection('process').aggregate([

    {

        $match :{"xx":{$in:["xx1","xx2"]}}

    },

    {

        $sort:{"create_time":-1}

    },

    {

        $skip :14

    },

    {

      $limit:1

    },

    {

        $unwind: { 

            path: "$processResult.factor_list",

            includeArrayIndex: "arrayIndex",

            preserveNullAndEmptyArrays: true

        }

    },

    {

        $project : {

            source_id : 1 ,

            create_at: '$create_time',

            credit_id: 1,

            _id:0,

            hello:"asd",

            event_code :1 ,

            processResult:'$processResult.factor_list'

           

        }

    },

    {

        $sort:{"processResult.name":-1}

    },

     {

      $limit:10

    },

    {

        $match :{"processResult.type":{$eq:"router"}}

    },

   

     {

        $group:{

              _id : "$source_id", 

              count: {$sum : 1},

              max_eventcode:{ "$max":"$event_code"},

              min_eventcode:{ "$min":"$event_code"},

              avg_eventcode:{ "$avg":"$event_code"},

              factor_types_list:{"$push":"$processResult.type"},

              factor_types_set:{"$addToSet":"$processResult.type"},

              firstcreditid:{"$first":"$credit_id"},

              lastcreditid:{"$last":"$credit_id"}

        }

    },

 {

        $group:{

              _id :  {'a': '$a', 'b': '$b', 'D': '$D'}, 

              count: {$sum : 1},

              max_eventcode:{ "$max":"$event_code"},

              min_eventcode:{ "$min":"$event_code"},

              avg_eventcode:{ "$avg":"$event_code"},

              factor_types_list:{"$push":"$processResult.type"},

              factor_types_set:{"$addToSet":"$processResult.type"},

              firstcreditid:{"$first":"$credit_id"},

              lastcreditid:{"$last":"$credit_id"}

        }

    },

  {$out: 'hh_col’},

   {

        $match :{"count":{$gt:5}}

    },

    ]

    ,{allowDiskUse: true}

)

聚合管道的优化 http://www.mongoing.com/docs/core/aggregation-pipeline-optimization.html

聚合管道的限制 http://www.mongoing.com/docs/core/aggregation-pipeline-limits.html

聚合管道和分片集合 http://www.mongoing.com/docs/core/aggregation-pipeline-sharded-collections.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值