Mongodb-聚合命令(一)

之前介绍了聚合中的管道操作符,今天介绍聚合命令 主要有count(),distinct(),group() 

1.count 

count是最简单的聚合工具,用于返回集合中的文档数量,与SQL中的count()一样

如一个空集合插入2条数据

>db.bitest.insert({"memid": "c001"})
>db.bitest.insert({"memid": "c002"})

统计文档数量

>db.bitest.count()
2

count可以添加条件

>db.bitest.count({"memid":"c001"})
1

2.distinct 

用法也同SQL的distinct相同,用来找出给定键的所有不同的值,使用时必须指定集合和键

格式如下:

>db.runCommand({distinct: "collection",key:"keyname"})

如果一个sorder集合有5笔订单记录

{"memid": "c001", "sorderno": "a001", "price":20}
{"memid": "c002", "sorderno": "a002", "price":80}
{"memid": "c001", "sorderno": "a003", "price":60}
{"memid": "c003", "sorderno": "a004", "price":30}
{"memid": "c001", "sorderno": "a005", "price":80}

想要统计出有几个下单账号,需要对memid使用distinct

>db.runCommamd({"distinct": "sorder", "key": "memid"})
{"values":["c001","c002","c003"],"ok":1}

3.group

使用group可以进行更复杂的聚合,用法同SQL的Group by

格式如下:

{
  group:
   {
     ns: <namespace>,
     key: <key>,
     $reduce: <reduce function>,
     $keyf: <key function>,
     cond: <query>
   }
}

-ns : 指定要进行分组的集合

-key:指定文档分组依据的键

-“$Reduce”  这个函数在集合内的每个文档上执行,该函数接受两个参数:当前文档和累加器文档

-keys :可选,替代key字段,指定一个函数创建一个key作为分组的键

-cond:过滤条件

有如下集合:

{"_id" : ObjectId("45de56y678j9i7880f"), "sorderno": "s01",  "date": ISODate("2018-01-04T16:00:00Z"), "orderamount": "50"}
{"_id" : ObjectId("346hy8790ju678tt56"), "sorderno": "s02",  "date": ISODate("2018-01-04T16:00:00Z"), "orderamount": "80"}
{"_id" : ObjectId("566hy8790ju658ft56"), "sorderno": "s03",  "date": ISODate("2018-01-05T16:00:00Z"), "orderamount": "80"}
{"_id" : ObjectId("576hy8790j8i78ui56"), "sorderno": "s04",  "date": ISODate("2018-01-05T16:00:00Z"), "orderamount": "80"}
{"_id" : ObjectId("786h48790ju898yt56"), "sorderno": "s05",  "date": ISODate("2018-01-06T16:00:00Z"), "orderamount": "80"}

对日期进行分组,统计每天的订单金额

>db.sorder.group({
    key: { date:1},
    initial : {"totalamount":0},
    reduce : function Reduce(doc, out) {
    out.totalamount+=doc.orderamount
   } });
[
    { 
        "date": ISODate("2018-01-04T16:00:00Z"),
        "totalamount": 130
    },
    { 
        "date": ISODate("2018-01-05T16:00:00Z"),
        "totalamount": 160
    },
    { "date": ISODate("2018-01-06T16:00:00Z"),
    "totalamount": 80
    },
]

后续还会继续介绍一些操作
更多文章可查看此处:http://forum.foxera.com/mongodb/category/27/server-shell
posted @ 2018-07-13 11:07  tingcheng  阅读(693)  评论(0编辑  收藏  举报