MongoDB2.2.0新特性之Aggregation Framework

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介绍:
提供了强大的运算符和各种函数

相关资源链接:
 
 








评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值