MongoDB 聚合
1.count()函数返回集合中文档的数量
2.distinct找出给定键的所有不同的值。
> db.users.insert({"name":"Ada","age":20})
> db.users.insert({"name":"Fred","age":35})
> db.users.insert({"name":"Susan","age":60})
> db.users.insert({"name":"Andy","age":35})
> db.runCommand({"distinct":"users","key":"age"})
{
"values" : [
20,
35,
60
],
"stats" : {
"n" : 4,
"nscanned" : 4,
"nscannedObjects" : 4,
"timems" : 0
},
"ok" : 1
}
3.group选定分组所依据的键,而后将集合依据选定键值的不同分成若干组,然后通过聚合每一组内的文档,产生一个结果文档。
> db.users.insert({"name":"Ada","age":34,"dept":"A"})
> db.users.insert({"name":"Cada","age":24,"dept":"A"})
> db.users.insert({"name":"Eva","age":15,"dept":"A"})
> db.users.insert({"name":"Yousg","age":15,"dept":"B"})
> db.users.insert({"name":"Tesg","age":51,"dept":"B"})
> db.users.insert({"name":"Gdsg","age":21,"dept":"B"})
> db.users.insert({"name":"GSa","age":22,"dept":"C"})
> db.users.insert({"name":"Rea","age":32,"dept":"C"})
> db.users.insert({"name":"Jeea","age":36,"dept":"C"})
> db.runCommand({"group":{"ns":"users","key":"dept","initial":{"age":0},"$reduce
":function(doc,prev){if(doc.age>prev.age){prev.age=doc.age,prev.name=doc.name}}}
})
{
"retval" : [
{
"age" : 51,
"name" : "Tesg"
}
],
"count" : 9,//时间文档总数
"keys" : 1,//key有多少个不同的值,此处返回有误不知何原因?
"ok" : 1
}
上面例子中ns指定了集合名称,key指定分组key值,initial指定初始化值,$reduce 函数会传递两个参数,当前文档和累加器文档(本组当前的结果)
还可以使用如下的方式
> db.users.group({"key":"dept",initial:{"age":0},"$reduce":function(doc,prev){if
(doc.age>prev.age){prev.age=doc.age,prev.name=doc.name}}});
[ { "age" : 51, "name" : "Tesg" } ]
为什么我两种方式下得到的结果都是错误的?
4.使用完成器
在group函数中指定“finalize”函数,在每组结果传递到客户端之前被调用。
5.将函数作为键使用
在分组函数中使用“$keyf”指定一个函数处理键值。
6.MapReduce
例子一:找出集合中所有的键
> map=function(){for(var key in this){emit(key,{count:1})}};
function () {
for (var key in this) {
emit(key, {count:1});
}
}
> reduce=function(key,emits){var total=0;for(var i in emits){total+=emits[i].cou
nt;}return {"count":total};}
function (key, emits) {
var total = 0;
for (var i in emits) {
&