MongoDB2.2.0新特性之Aggregation Framework

来源:互联网 发布:手机网络个人理财产品 编辑:程序博客网 时间:2024/05/17 09:45
2.2.0新加的一个很好用的框架
两个概念pipeline类似于linux shell中的管道操作,用于对文档进行过滤和修改; 
                  expression用于对pipeline指令进行逻辑运算
如何使用?db.people.aggregate( [<pipeline>] )

pipeline介绍:
原始文档:
{  title : "this is my title" ,  author : "bob" ,  posted : new Date() ,  pageViews : 5 ,  tags : [ "fun" , "good" , "fun" ] ,  comments : [      { author :"joe" , text : "this is cool" } ,      { author :"sam" , text : "this is bad" }  ],  other : { foo : 5 }}
1.$project 可以理解成表列的投影操作,可以增加、删除、重命名和定义子对象作为返回列(尤其这个比较NB!)
   i.e. db.article.aggregate(
    { $project : {        title : 1 ,        stats : {            pv : "$pageViews",            foo : "$other.foo",            dpv : { $add:["$pageViews", 10] }        }    }});
2. $match 相当于一个query,将这个pipeline放在开始处能有效过滤文档,并能使用索引
  i.e. db.article.aggregate(
    { $match : { score  : { $gt : 50, $lte : 90 } } });
3. $limit $skip 不多解释

4.$unwind 将数组中的元素进行分裂,得到的文档数=数组元素数,这些文档只有指定列不同
  i.e. db.article.aggregate(
    { $project : {        author : 1 ,        title : 1 ,        tags : 1    }},    { $unwind : "$tags" })
    {
     "result" : [             {                     "_id" : ObjectId("4e6e4ef557b77501a49233f6"),                     "title" : "this is my title",                     "author" : "bob",                     "tags" : "fun"             },             {                     "_id" : ObjectId("4e6e4ef557b77501a49233f6"),                     "title" : "this is my title",                     "author" : "bob",                     "tags" : "good"             },             {                     "_id" : ObjectId("4e6e4ef557b77501a49233f6"),                     "title" : "this is my title",                     "author" : "bob",                     "tags" : "fun"             }     ],     "OK" : 1}
5.$group 吃内存
   i.e. db.article.aggregate(
    { $group : {        _id : "$author",        docsPerAuthor : { $sum : 1 },        viewsPerAuthor : { $sum : "$pageViews" }    }});
6.$sort 吃内存
 i.e. db.users.aggregate(
    { $sort : { age : -1, posts: 1 } });
Expression介绍:
提供了强大的运算符和各种函数

相关资源链接:
http://docs.mongodb.org/manual/reference/aggregation/ API
http://docs.mongodb.org/manual/aggregation/#aggregation-framework 聚合框架目录