目录
摘要
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