yzq 发表于 2015-7-10 10:37:02

mongodb Aggregation Framework 简单记录

  Aggregation Framework参数解析如下:
  $match:
过滤数据通过设置一个条件将数据进行筛选过滤
db.runCommand({ aggregate : "article", pipeline : [{ $match : { author : "dave" } }]});
$match只是pipeline中的一环,它筛选的结果数据可以再进行下一级的统计操作。
$project:
命令用于设定数据的筛选字段,就像我们SQL中select需要的字段一样。
db.runCommand({ aggregate : "article", pipeline : [{ $match : { author : "dave" } },{ $project : { _id : 0,author : 1,tags : 1}}]});
===db.article.find({ author : "dave" }, { _id : 0, author : 1, tags : 1);
上面就是将所有author为dave的记录的author和tags两个字段取出来。(_id:0 表示去掉默认会返回的_id字段).
  $unwind:因为意思是松开、解开、展开,他可以将某一个为array类型字段的数据拆分成多条,每一条包含array中的一个属性。
db.article.save( {
    title : "this is your title" ,
    author : "dave" ,
    posted : new Date(4121381470000) ,
    pageViews : 7 ,
    tags : [ "fun" , "nasty" ] ,
    comments : [
      { author :"barbara" , text : "this is interesting" } ,
      { author :"jenny" , text : "i like to play pinball", votes: 10 }
    ],
    other : { bar : 14 }
});
  这里面tags字段就是一个array。下面我们在这个字段上应用$unwind操作
db.runCommand({ aggregate : "article", pipeline : [{ $unwind : "$tags" ]});
  $group:
功能就是按某一个key将key值相同的多条数据组织成一条.
db.article.save( {
    title : "this is some other title" ,
    author : "jane" ,
    posted : new Date(978239834000) ,
    pageViews : 6 ,
    tags : [ "nasty" , "filthy" ] ,
    comments : [
      { author :"will" , text : "i don't like the color" } ,
      { author :"jenny" , text : "can i get that in green?" }
    ],
    other : { bar : 14 }
});
我们可以先用上面的$unwind按tags将记录拆成多条,然后再将记录按tags字段重新组织,将同一个tag对应的所有author放在一个array中
db.runCommand({ aggregate : "article", pipeline : [
    { $unwind : "$tags" },
    { $group : {
_id : "$tags",
      count : { $sum : 1 },
authors : { $addToSet : "$author" }
    }}
]});
  db.runCommand({ aggregate : "gc_postsfield", pipeline : [
    { $match : {cate1:1121} },
    { $group : {
_id : "$cate1",
      count : { $sum : 1 },
    }}
]});
  
  
  
  
  
页: [1]
查看完整版本: mongodb Aggregation Framework 简单记录