Mongodb聚合函数

 

插入 测试数据

复制代码
for(var j=1;j<3;j++){    
for(var i=1;i<3;i++){    var person={Name:"jack"+i,Age:i,Address:["henan","wuhan"],Course:[{Name:"shuxue",Score:i},{Name:"wuli",Score:i}]}db.DemoTest.Person.insert(person)     
}
}
复制代码

 

Count

db.DemoTest.Person.count({Name:"jack1"})

返回数量

 

 distinct

db.DemoTest.Person.distinct("Name")

返回不重复的Name值。

 

 group

例子:按照Name分组,条件是Age大于46

复制代码
db.DemoTest.Person.group({"key":{"Name":true}, -----分组的keky"initial":{"Person":[]},-------每组分享的一个”初始化函数“"$reduce":function(cur,prev){   ------这个函数的第一个参数是当前的文档对象,第二个参数是上一次function操作的累计对象,第一次为initial中的{”person“:[]}。有多少个文档, $reduce就会调用多少次

prev.Person.push(cur);
},"finalize":function(prev){   ---返回每组的数量     prev.count=prev.Person.length;  },"condition":{"Age":{"$lt":46}}   -----过滤条件})
复制代码

返回结果如下:

 返回的json

 

 mapReduce

 mapReduce其实是一种编程模型,用在分布式计算中,其中有一个“map”函数,一个”reduce“函数。

   map:

          这个称为映射函数,里面会调用emit(key,value),集合会按照你指定的key进行映射分组。

   reduce:

         这个称为简化函数,会对map分组后的数据进行分组简化,注意:在reduce(key,value)中的key就是

      emit中的key,vlaue为emit分组后的emit(value)的集合,这里也就是很多{"count":1}的数组。

   mapReduce:

          这个就是最后执行的函数了,参数为map,reduce和一些可选参数。

 

在MongoDB存储的文档上执行聚合操作非常有用,这种方式的一个限制是聚合函数(比如,SUM、AVG、MIN、MAX)需要通过mapper和reducer函数来定制化实现。

MongoDB没有原生态的用户自定义函数(UDFs)支持。但是它允许使用db.system.js.save命令来创建并保存JavaScript函数,JavaScript函数可以在MapReduce中复用。

 

第一种统计方式--对应集合直接统计

1.在MongoDB javascript Shell中对Array对象进行了一些扩展,其中新增sum方法,以方便统计数据之用的。

复制代码
Array.sum=function(arr){
if(arr.length == 0)
return null;
var s = arr[0];
for(var i = 1; i < arr.length; i++)
s += arr[i];
return s;
}
复制代码

2.例子:按照名称分组,统计每组年龄的和,条件是年龄小于2.

如果统计数量:var map = function(){ emit(this.Name, 1); }   其实是让值永远为1

var map = function(){ emit(this.Name, this.Age); }
var reduce = function( key, values ){ return Array.sum(values); }
var options = {query: { Age: {$lt: 2} }, out: { inline : 1 }}
db.Person.mapReduce(map,reduce,options)

结果如下

 结果json

 

分析一下:
1. map部分
作用:用于分组的。
emit(param1, param2)
param1:需要分组的字段,this.字段名。
param2:需要进行统计的字段,this.字段名。

2. reduce部分
作用:处理需要统计的字段
var reduce = function(key, values){
......统计字段处理
}
key: 指分组字段(emit的param1)对应的值
values:指需要统计的字段(emit的param2)值组成的数组

简单介绍统计常用的方法:
* 对数值类型进行求和

1
2
3
4
<span style="font-size: 16px;">var reduce = function(key, values){
return Array.sum(values);
}
</span>

* 对字符串类型进行拼凑

1
2
3
<span style="font-size: 16px;">var reduce = function(key, values){
return values.join(', ');
}</span>

3. options部分
{ query: { age: {$lt: 25} }, out: "name_totals" }
query:先筛选符合条件的记录出来,再进行分组统计。
out:将分组统计后的结果输出到哪个集合当中。
默认情况下,out所指定的集合在数据库断开连接后再次打开时,依旧存在,并保留之前的所有记录的。

4. 执行分组统计
>db.集合名.mapReduce( map, reduce, options )

 

第二种统计方式--命令统计

1.命令如下:

注意:out参数 out:"Person_Name" 代表会创建一个临时表Person_Name 然后再从临时表中查找,out:{inline:1} 代表直接显示在当前命令执行的结果中

复制代码
var map = function(){ emit(this.Name, this.Age); }
var reduce = function( key, values ){ return Array.sum(values); }
db.runCommand({mapreduce:"Person",map:map,reduce:reduce,out:"Person_Name",keeptemp: false,query: { Age:{ $lt: 2 }},sort:{ Name:1},
limit:3
})
复制代码

 解析:
mapreduce:
分组统计的集合名
eg:
mapreduce: 'mythings'
不能写成mapreduce: mythings,否则报异常:mythings is not defined

map,reduce :
同上,不做阐述

out :
将分组统计结果输出到某个集合。
注意:不能缺省,必须指定名称,否则报错,报错如下:
“exception: 'out' has to be a string or an object”

keeptemp :
是否保留临时集合(指out指定的集合)
keeptemp:false时会在数据库断开连接后,MongoDB会移除该集合的所有记录。而不是删除。
keeptemp:true时即使数据库断开连接后,再次连接上,该临时集合依旧保持之前所有记录。
keeptemp默认值为true。

query :
筛选记录后,再进行分组统计
eg:
query: { age:{ $lt: 25 }}

sort :
对分组统计的集合进行排序,也即先排序,后再执行分组统计的。
注意:这里的排序需要用到索引,必须先创建索引。

limit :

对分组统计的集合先进行限制返回记录的条数,然后再去进行统计操作。注意:不要理解成对统计后的结果进行限制返回记录条数。

verbose :
显示时间统计信息,取值为true/false

转载于:https://www.cnblogs.com/wangjing666/p/6837131.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/541396.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

php rename函数_php rename函数怎么用

PHP rename()函数用于重命名文件或目录&#xff0c;语法“rename(文件旧名称,新名称,句柄环境)”&#xff0c;使用用户指定的新名称更改文件或目录的旧名称&#xff0c;并且可以根据需要在目录之间移动&#xff1b;成功时返回True&#xff0c;失败时返回False。php rename()函数…

Java BigInteger类| xor()方法与示例

BigInteger类的xor()方法 (BigInteger Class xor() method) xor() method is available in java.math package. xor()方法在java.math包中可用。 xor() method is used to perform xor operation between this BigInteger and the given BigInteger and we all know when we pe…

Spring Data Redis实战之提供RedisTemplate

为什么80%的码农都做不了架构师&#xff1f;>>> 参考&#xff1a; http://www.cnblogs.com/edwinchen/p/3816938.html 本项目创建的是Maven项目 一、pom.xml引入dependencies <dependency><groupId>org.springframework.data</groupId><artif…

Java BigInteger类| and()方法与示例

BigInteger类和()方法 (BigInteger Class and() method) and() method is available in java.math package. and()方法在java.math包中可用。 and() method is used to perform and operation between this BigInteger and the given BigInteger (val) [i.e. (this BigInteger)…

php映射,PHP实现路由映射到指定控制器

自定义路由的功能&#xff0c;指定到pathinfo的url上,再次升级之前的脚本SimpleLoader.phpclass SimpleLoader{public static function run($rulesarray()){header("content-type:text/html;charsetutf-8");self::register();self::commandLine();self::router($rule…

stl vector 函数_vector :: clear()函数,以及C ++ STL中的示例

stl vector 函数C vector :: clear()函数 (C vector::clear() function) vector::clear() is a library function of "vector" header, it is used to remove/clear all elements of the vector, it makes the 0 sized vector after removing all elements. vector …

Commonjs规范及Node模块实现

前面的话 Node在实现中并非完全按照CommonJS规范实现&#xff0c;而是对模块规范进行了一定的取舍&#xff0c;同时也增加了少许自身需要的特性。本文将详细介绍NodeJS的模块实现 引入 nodejs是区别于javascript的&#xff0c;在javascript中的顶层对象是window&#xff0c;而在…

thinkphp3 php jwt,ThinkPHP5 使用 JWT 进行加密

- 使用 Composer安装此扩展- 代码示例<?php /*** [InterCommon-接口公用]* Author RainCyan* DateTime 2019-08-12T16:38:080800*/namespace app\hladmin\controller;use think\Controller;use \Firebase\JWT\JWT;class InterCommonController extends Controller {private…

数据管理与商业智能_商业智能与数据科学

数据管理与商业智能In this heavily jargonized trade, the words typically overlap one another, leading to a scarcity of understanding or a state of confusion around these ideas. whereas big data vs analytics or computing vs machine learning vs cognitive inte…

JavaWeb网上图书商城完整项目--day02-14.登录功能的login页面处理

1、现在注册成功之后&#xff0c;我们来到登录页面&#xff0c;登录页面在于 在登录页面。我们也需要向注册页面一样对登录的用户名、密码 验证码等在jsp页面中进行校验&#xff0c;校验我们单独放置一个login.js文件中进行处理&#xff0c;然后login.jsp加载该js文件 我们来看…

php多线程是什么意思,多线程是什么意思

线程是操作系统能够进行运算调度的最小单位&#xff0c;它被包含在进程之中&#xff0c;是进程中的实际运作单位&#xff0c;而多线程就是指从软件或者硬件上实现多个线程并发执行的技术&#xff0c;具有多线程能力的计算机因有硬件支持而能够在同一时间执行多于一个线程&#…

c++一个类创建多个对象_C ++ | 创建一个类的多个对象

c一个类创建多个对象In the below program, we are creating a C program to create multiple objects of a class. 在下面的程序中&#xff0c;我们正在创建一个C 程序来创建一个类的多个对象 。 /* C program to create multiple objects of a class */#include <iostrea…

Activity中与ListActivity中使用listview区别

一.Activity中与ListActivity中使用listview区别&#xff08;本身没多大区别&#xff0c;只是ListActivity在listview的显示上做了一些优化&#xff09;Activity中使用Listview步骤&#xff1a;1.xml布局中,ListView标签id可以任意取值如&#xff1a;<ListView andro…

java相关是什么,什么是java

java基础常见面试题&#xff0c;这是一篇超长的随笔&#xff01;&#xff01;&#xff01;1. Java基础部分....................................................... 4 1、一个".java"源文件中是否可以包括多个类(不是内部类)&#xff1f;有什么限制&#xff1f;.. …

如何在Scala中将Double转换为String?

Double in Scala is a data type that stores numerical values that have decimals. It can store a 64-bit floating point number. Scala中的Double是一种数据类型&#xff0c;用于存储带有小数的数值。 它可以存储一个64位浮点数。 Example: 例&#xff1a; val decimal…

basic knowledge

Position 属性&#xff1a;规定元素的定位类型。即元素脱离文档流的布局&#xff0c;在页面的任意位置显示。 ①absolute &#xff1a;绝对定位&#xff1b;脱离文档流的布局&#xff0c;遗留下来的空间由后面的元素填充。定位的起始位置为最近的父元素(postion不为static)&…

avatar.php uid,phpcms函数库中获取会员头像方法get_memberavatar()有时无效问题

修复方法&#xff1a;首先我先给出无效情况的演示代码&#xff0c;如下&#xff1a;$userid intval($_GET[userid]);$userinfo $this->db->get_one(userid.$userid);$this->db->set_model(10); //原因便在这里$userdetail $this->db->get_one("useri…

ruby 集合 分组_将Ruby中两个集合的所有元素结合在一起

ruby 集合 分组In this program, we will see how we can combine the two sets? This is not a very difficult task. This can be easily done with the help of the operator. In many places of programming, you will find that operator is overloaded for various ty…

​Python中面向对象的编程

Python面向对象的编程1概述&#xff08;1&#xff09;面向对象编程面向对象的编程是利用“类”和“对象”来创建各种模型来实现对真实世界的描述&#xff0c;使用面向对象编程的原因一方面是因为它可以使程序的维护和扩展变得更简单&#xff0c;并且可以大大提高程序开发效率&a…

php中用for循环制作矩形,PHP中for循环语句的几种变型

PHP中for循环语句的几种变型2021-01-22 10:21:42406for语句可以说是PHP(同时也是多种语言)的循环控制部份最基本的一个语句了&#xff0c;for语句的执行规律和基础用法在这里就不多说&#xff0c;可以参见PHP手册for语句部分。PHP手册中对它的语法定义如下&#xff1a;for(expr…