Step into MongoDB - 08 - 聚合查询

目录

摘要

count,distinct,group

聚合

count

格式

count([cond])

增加查询条件会让 count 变慢

db.phones.count({ 'components.number' : { $gt : 559999 }})

distinct

distinct 将结果聚合成一个数组,用于返回指定键的所有不同值

db.phones.distinct( 'components.number' , { 'components.number' : { $lt : 555005 }}})

group

group 类似 SQL 中的 Group By 语句。

如果对 Mongo 集合进行了分片,那么 group 就无效了。

db.phones.group({
    initial : { count : 0 },
    reduce : function(phone, output) { output.count++; },
    cond : { 'components.number' : { $gt : 559999 } },
    key : { 'components.area' : true }
})

参数

  • key 指定按其分组的字段,可省略
  • cond 指定的值的范围
  • reduce 指定用于管理如何输出值的函数,函数的第一个参数为当前 doc,第二个参数为输出对象
  • initial 创建字段,此字段会显示在输出中
  • finalize 完成器,指定在返回值之前的最后一刻执行的函数,用以精简从数据库传到用户的数据

test 集合中有如下数据 {"x":1}{"x":2}{"x":3}{"x":4}{"x":5}{"x":6}{"x":1}{"x":3}

执行如下语句

db.test.group({
        initial : { count : 0 },    //在输出结果中创建字段 count
        cond : {},
        key : { "x" : true },
        reduce : function (test, out){
           out.count++; //更新输出结果中的 count 字段
        },
        finalize : function (out){
            return out.count > 1 ? out : "";
        }
})

输出结果

{
    "0" : {
        "x" : 1,
        "count" : 2
    },
    "1" : "",
    "2" : {
        "x" : 3,
        "count" : 2
    },
    "3" : "",
    "4" : "",
    "5" : ""
}

另一例子

db.phones.group({
    initial : { prefixes : {} },
    reduce : function(phone, output) { output.prefixes[phone.components.prefix] = 1; },
    cond : { 'components.number' : { $gt : 559999 } },
    key : { 'components.area' : true },
    finalize : function(out){
        var arr = [];
        for (var p in out.prefixes){
            arr.push(  parseInt(p) );
        }
        out.prefixes = arr;
    }
})[0].prefixes
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值