Home > Database > Mysql Tutorial > body text

单一目的聚集操作

WBOY
Release: 2016-06-07 15:59:11
Original
1027 people have browsed it

聚集指的是,基于一个输入和特定程序来计算结果的数据操纵操作的广泛类别。 MongoDB提供了大量在结果集上执行特定聚集操作的聚集操作方法。 尽量在使用范围上有限制,特别是和聚集管道、map-reduce相比较,但这些操作,为常规的数据处理提供了直接的语义。 C

聚集指的是,基于一个输入和特定程序来计算结果的数据操纵操作的广泛类别。

MongoDB提供了大量在结果集上执行特定聚集操作的聚集操作方法。

尽量在使用范围上有限制,特别是和聚集管道、map-reduce相比较,但这些操作,为常规的数据处理提供了直接的语义。

Count

MongoDB可以返回符合一个query的文档数量。count命令,以及count()和cursor.count()方法提供访问mongo shell里面的计数(counts)。

例子:

假设一个名叫records的集合,仅有下面这些文档:

{ a: 1, b: 0 }
{ a: 1, b: 1 }
{ a: 1, b: 4 }
{ a: 2, b: 2 }
Copy after login
下面的操作会计算在集合里面的所有文档的数目,并返回4
db.records.count()
Copy after login
下面的操作只会对a字段值为1计数,返回结果为3
db.records.count( { a: 1 } )
Copy after login
译者注:

很多朋友可能对上面的shell脚本转化成实际编程语言感动困难。实际上,mongoDB提供的API都很友好,和上面的shell基本有对应关系。以Java为例,

// db是取得的数据库
DBCollection collection = db.getCollection("record");
BasicDBObject query = new BasicDBObject();
query.put("a",1);
int result = collection.count(query);
Copy after login
再举个例子,笔者最近做的一个项目,有这个一个需求:统计当天新注册用户量。
query.put("registertime",new BasicDBObject("$gt",HeartDateUtil.getStartDateOfToday()));
collection.count(query);
Copy after login
其中HeartDateUtil.getStartDateOfToDay是一个工具方法,用来返回今天开始的Date.

Distinct

Distinct操作匹配查询的文档,返回在匹配文档里该字段的所有唯一值。在Mongo shell里面提供了distinct命令和db.collection.distinct()方法。考虑下面的操作:

\

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!