Definition
定义
count
计数
    Counts the number of documents in a collection. Returns a document that contains this count and as well as the command status.
     统计某个集合中文档的数量。返回一个包含计数和命令状态的文档。
     例如:{ "shards" : { "s1" : 5 }, "n" : 5, "ok" : 1 }

count has the following form:
    计数有以下格式:

    {count: <collection-name>,query: <document>,limit: <integer>,skip: <integer>,hint: <hint>,readConcern: <document>}

例如:

mongos> db.runCommand(
...    {
...      count:"codetest1",
...      query:{ "deviceCode" : "2017014504"},
...      limit:10,
...      skip:1,
...      hint:"deviceCode_1"
...    }
... )

返回结果:{ "shards" : { "s1" : 11 }, "n" : 10, "ok" : 1 }

count has the following fields:
    计数有以下几个字段:
    Field  Type   Description
    count  string   The name of the collection to count.
    计数,字符类型,计数集合的名称。
    query  document    Optional. A query that selects which documents to count in a collection.
     查询,文档类型,可选。查询集合中哪些要计数的文档。
    limit     integer Optional. The maximum number of matching documents to return.
    限制,整数,可选。返回匹配文档的最大行数。
    skip integer     Optional. The number of matching documents to skip before returning results.
     跳跃,整数,可选。在返回结果集前,跳过匹配文档的行数。
    hint string or document   
    强制,字符类型或者文档类型
    Optional. The index to use. Specify either the index name as a string or the index specification document.
    可选。强制使用索引。如果使用字符类型则指定索引名称,如果使用文档类型则指定索引文档。
    New in version 2.6.
    readConcern    document    
    读策略,文档类型。
    Optional. Specifies the read concern. The default level is "local".
    可选。指定读内容。默认级别为"local"。
    To use a read concern level of "majority", you must use the WiredTiger storage engine and start the mongod instances with the --enableMajorityReadConcern command line option (or the replication.enableMajorityReadConcern setting if using a configuration file).
    如果将级别设置为"majority",你必须使用WiredTiger存储引擎,并且在启动mongod实例时指定--enableMajorityReadConcern参数)(或者在config参数配置文档中指定replication.enableMajorityReadConcern参数)。
博文参考:MongoDB readConcern 原理解析
    Only replica sets using protocol version 1 support "majority" read concern. Replica sets running protocol version 0 do not support "majority" read concern.
    只有副本集使用"protocol version 1 "才支持"majority"读策略。副本集运行"protocol version 0"不支持"majority"读策略。
    To ensure that a single thread can read its own writes, use "majority" read concern and "majority" write concern against the primary of the replica set.
     要确保单个线程可以读取其自己的写入,请针对副本集的主数据库使用"majority"读取关注和"majority"写入关注。
    To use a read concern level of "majority", you must specify a nonempty query condition.
    为了使用读关注级别"majority",必须指定一个非空的查询条件。
    New in version 3.2.
    版本3.2新功能
    MongoDB also provides the count() and db.collection.count() wrapper methods in the mongo shell.
    MongoDB在mongo shell窗口可以使用count()和db.collection.count()进行查询。
Behavior
行为
On a sharded cluster, count can result in an inaccurate count if orphaned documents exist or if a chunk migration is in progress.
在分片集合中,如果存储孤立文档或者Chunk正在迁移,则会导致计数的结果可能会不正确。

To avoid these situations, on a sharded cluster, use the $group stage of the db.collection.aggregate() method to $sum the documents. For example, the following operation counts the documents in a collection:
为了避免分片集群发生这种情况,使用db.collection.aggregate()命令中的$group方法进行文档$sum求和。例如以下对一个集合进行计数操作

db.collection.aggregate([{ $group: { _id: null, count: { $sum: 1 } } }]
)

To get a count of documents that match a query condition, include the $match stage as well:
为了统计满足查询条件的文档数量,可以使用$match方法。

db.collection.aggregate([{ $match: <query condition> },{ $group: { _id: null, count: { $sum: 1 } } }]
)

See Perform a Count for an example.
下面执行一下计数的例子。
The following example selects documents to process using the $match pipeline operator and then pipes the results to the $group pipeline operator to compute a count of the documents:
以下例子先使用$match管道方法过滤出文档,然后将结果传输给$group管道方法来完成文档计数。

db.articles.aggregate( [{ $match: { $or: [ { score: { $gt: 70, $lt: 90 } }, { views: { $gte: 1000 } } ] } },{ $group: { _id: null, count: { $sum: 1 } } }
] );

In the aggregation pipeline, $match selects the documents where either the score is greater than 70 and less than 90 or the views is greater than or equal to 1000. These documents are then piped to the $group to perform a count. The aggregation returns the following:
在聚合管道中,$match查询出满足条件的文档,即分数大于79,且小于90的文档;或者阅读量大于等于1000的文档。查询出来的文档传给$group方法完成计数。聚合返回的结果如下:
{ "_id" : null, "count" : 5 }

Accuracy after Unexpected Shutdown
意外关机后的准确性
After an unclean shutdown of a mongod using the Wired Tiger storage engine, count statistics reported by count may be inaccurate.
如果一个mongod进程(使用Wired Tiger存储引擎)未正常关闭,计数统计出现可能会不正确。

The amount of drift depends on the number of insert, update, or delete operations performed between the last checkpoint and the unclean shutdown. Checkpoints usually occur every 60 seconds. However, mongod instances running with non-default --syncdelay settings may have more or less frequent checkpoints.
偏差值取决于在最后一个检查点和不正常关闭之间执行的插入,更新或删除操作的数量。 检查点通常每60秒发生一次。 但是,使用非默认--syncdelay设置运行的mongod实例可能有更多或更少的频繁检查点。
Run validate on each collection on the mongod to to restore the correct statistics after an unclean shutdown.
在不正常关闭后,在mongod上对每个集合运行validate以恢复正确的统计信息。
Note
注意
This loss of accuracy only applies to count operations that do not include a query document.
此精度影响仅适用于不包含查询文档的计数操作。
Examples
举例
The following sections provide examples of the count command.
以下内容举例演示计数命令操作。
Count All Documents
统计所有文档数。
The following operation counts the number of all documents in the orders collection:
以下计数操作统计orders命令中所有的文档数量。

db.runCommand( { count: 'orders' } )

In the result, the n, which represents the count, is 26, and the command status ok is 1:
返回结果中,n代表计数值是26条,并且命令执行状态ok是1。
{ "n" : 26, "ok" : 1 }

Count Documents That Match a Query
对于符合查询条件的文档计数
The following operation returns a count of the documents in the orders collection where the value of the ord_dt field is greater than Date('01/01/2012'):
以下操作统计orders集合中ord_dt字段值大于Date('01/01/2012')的文档数。

db.runCommand( { count:'orders',query: { ord_dt: { $gt: new Date('01/01/2012') } }} )

In the result, the n, which represents the count, is 13 and the command status ok is 1:
返回结果中,n代表计数值为13,并且命令状态ok值为1。
{ "n" : 13, "ok" : 1 }

Skip Documents in Count
跳过文档计数
The following operation returns a count of the documents in the orders collection where the value of the ord_dt field is greater than Date('01/01/2012') and skip the first 10 matching documents:
以下操作统计orders集合中ord_dt字段大于Date('01/01/2012') 并且跳过前10条匹配文档的数量。

db.runCommand( { count:'orders',query: { ord_dt: { $gt: new Date('01/01/2012') } },skip: 10 }  )

In the result, the n, which represents the count, is 3 and the command status ok is 1:
返回结果中,n代表计数值为3,并且命令状态ok值为1。
{ "n" : 3, "ok" : 1 }

Specify the Index to Use
计数中指定索引

The following operation uses the index { status: 1 } to return a count of the documents in the orders collection where the value of the ord_dt field is greater than Date('01/01/2012') and the status field is equal to "D":
以下计数操作是使用orders集合中的索引 { status: 1 } ,并且统计ord_dt字段大于Date('01/01/2012')并且status字段值为"D"

db.runCommand({count:'orders',query: {ord_dt: { $gt: new Date('01/01/2012') },status: "D"},hint: { status: 1 }}
)

In the result, the n, which represents the count, is 1 and the command status ok is 1:
返回结果中,n代表计数值为1,并且状态ok为1。
{ "n" : 1, "ok" : 1 }

Override Default Read Concern
覆盖默认读关注
To override the default read concern level of "local", use the readConcern option.
为了覆盖默认读关注级别"local",使用readConcern选项。
The following operation on a replica set specifies a Read Concern of "majority" to read the most recent copy of the data confirmed as having been written to a majority of the nodes.
在副本集上指定读关注级别为"majority",为了读取当前已经同步到所有节点的数据。
Important
重要
    To use a read concern level of "majority", you must use the WiredTiger storage engine and start the mongod instances with the --enableMajorityReadConcern command line option (or the replication.enableMajorityReadConcern setting if using a configuration file).
为了使用 "majority"读关注级别,必须使用WiredTiger存储引擎,并且在启动命令行中加入--enableMajorityReadConcern选项(或者在参数配置文档中加入replication.enableMajorityReadConcern)。

Only replica sets using protocol version 1 support "majority" read concern. Replica sets running protocol version 0 do not support "majority" read concern.
只有副本集使用"protocol version 1 "才支持"majority"读关注。副本集运行"protocol version 0"不支持"majority"读策略。

To use the readConcern level of "majority", you must specify a nonempty query condition.
    为了使用读关注级别"majority",必须指定一个非空的查询条件。
    Regardless of the read concern level, the most recent data on a node may not reflect the most recent version of the data in the system.
    无论读取关注级别如何,节点上的最新数据可能不会反映系统中数据的最新版本。

db.runCommand({count: "restaurants",query: { rating: { $gte: 4 } },readConcern: { level: "majority" }}
)

To ensure that a single thread can read its own writes, use "majority" read concern and "majority" write concern against the primary of the replica set.
要确保单个线程可以读取其自己的写入,请针对副本集的主数据库使用"majority"读取关注和"majority"写入关注。

MongoDB聚合—计数count相关推荐

  1. php数据group去重,MongoDB_Mongodb聚合函数count、distinct、group如何实现数据聚合操作, 上篇文章给大家介绍了Mong - phpStudy...

    Mongodb聚合函数count.distinct.group如何实现数据聚合操作 上篇文章给大家介绍了Mongodb中MapReduce实现数据聚合方法详解,我们提到过Mongodb中进行数据聚合操 ...

  2. MongoDB聚合查询 Pipeline 和 MapReduce

    MongoDB聚合查询 MongoDB聚合查询 什么是聚合查询 Pipeline聚合管道方法 聚合流程 详细流程 聚合语法 常用聚合管道 $count $group $match $unwind $p ...

  3. mongoDB聚合操作_aggregate()归纳

    mongoDB聚合操作 文章目录 1.准备一组数据 2.$group 分组管道 2.1 统计单组 2.2 统计多组 3.$match 过滤管道 拓展 统计数据个数 4.$project 映射管道 5. ...

  4. MongoDB 聚合操作

    MongoDB 聚合操作 在MongoDB中,有两种方式计算聚合:Pipeline 和 MapReduce.Pipeline查询速度快于MapReduce,但是MapReduce的强大之处在于能够在多 ...

  5. MongoDB 聚合

    聚合操作过程中的数据记录和计算结果返回.聚合操作分组值从多个文档,并可以执行各种操作,分组数据返回单个结果.在SQL COUNT(*)和group by 相当于MongoDB的聚集. aggregat ...

  6. mongodb聚合查询-aggregate

    Mongodb-aggregate 在工作中经常遇到一些mongodb的聚合操作,和mysql对比起来,mongo存储的可以是复杂的类型,比如数组,字典等mysql不善于处理的文档型结构,但是mong ...

  7. MongoDB聚合(aggregate)常用操作及示例

    简介 MongoDB 中聚合(aggregate)主要用于处理数据(诸如统计平均值,求和等),并返回计算后的数据结果. 有点类似 SQL 语句中的 count(*). 常用操作 表达式 描述 $mat ...

  8. limit mongodb 聚合_mongodb-$type、limit、skip、sort方法、索引、聚合

    一.$type操作符 $type操作符是基于BSON类型来检索集合中匹配的数据类型,并返回结果. MongoDB 中可以使用的类型如下表所示: 类型数字备注 Double 1 String 2 Obj ...

  9. MongoDB 聚合管道(Aggregation Pipeline)

    管道概念 POSIX多线程的使用方式中, 有一种很重要的方式-----流水线(亦称为"管道")方式,"数据元素"流串行地被一组线程按顺序执行.它的使用架构可参考 ...

最新文章

  1. C#中的thread和task之Task
  2. 坑爹的公交卡充值的流程
  3. html5游戏面试题及答案,HTML5常见面试题及答案(二)
  4. csdn上传图片发现:缺少图像源文件地址
  5. php curl 无法获取网页内容,php curl获取网页内容(IPV6下超时)的解决办法
  6. Makefile:.d依赖文件
  7. python批量更改图片尺寸(保持长度和高度的长短关系)
  8. HUB、Switch、Router在OSI模型层次信息
  9. 三维建模的基础知识:SolidWorks /CATIA 简介
  10. Access2016学习6
  11. 【商品架构day4】十年前淘宝商品系统怎么做平台化
  12. python电子表格类_python合并同类型excel表格的方法
  13. DHU Python Curriculumly Learning【5】——大作业_key_by_TA
  14. 万能分页显示上一页下一页
  15. 工作一年的心得体会(持续中.......)
  16. 显著性检测学习笔记(2):DMRA__2019_ICCV
  17. 关于如何开启本地代理隐藏本地ip
  18. Java从键盘上输入一个正整数n,然后计算1+2+...+n的结果并输出
  19. 使用模拟器玩地下城与勇士M电脑版试玩分享
  20. 用计算机怎样提交作业,学而思培优如何提交作业 学而思培优在线操作说明之五步法...

热门文章

  1. 自动化用例设计原则+web自动化框架
  2. oracle 增加列 生效,oracle基础(表的创建,插入,修改,增加,列的问题)
  3. 注册php tp5,TP5登录注册
  4. 数据库设计_SQL数据库设计(数据建模)
  5. ML 12 13 mixture of gaussions and EM
  6. 拉格朗日(lagrange)插值及其MATLAB程序
  7. 模型保存的方法-----仅保存架构
  8. Android10 root,Android Q系统Magisk完美实现ROOT
  9. java 一个数组key一个数组value_在各种语言中,使用key在map中获取value 和 使用下标获取数组中的数据 相比哪个更快?...
  10. 抖音下拉词推广是什么?