$elemMatch (query)

https://www.mongodb.com/docs/manual/reference/operator/aggregation/count/

 

$count (aggregation)

 
 
$count
 

Passes a document to the next stage that contains a count of the number of documents input to the stage.

NOTE

Disambiguation

This page describes the $count aggregation pipeline stage. For the $count aggregation accumulator, see $count (aggregation accumulator).

$count has the following prototype form:

{ $count: <string> }
 

<string> is the name of the output field which has the count as its value. <string> must be a non-empty string, must not start with $ and must not contain the . character.

 

The $count stage is equivalent to the following $group + $project sequence:

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

where myCount would be the output field that contains the count. You can specify another name for the output field.

TIP

See also:

db.collection.countDocuments() which wraps the $group aggregation stage with a $sum expression.

 

A collection named scores has the following documents:

{ "_id" : 1, "subject" : "History", "score" : 88 }
{ "_id" : 2, "subject" : "History", "score" : 92 }
{ "_id" : 3, "subject" : "History", "score" : 97 }
{ "_id" : 4, "subject" : "History", "score" : 71 }
{ "_id" : 5, "subject" : "History", "score" : 79 }
{ "_id" : 6, "subject" : "History", "score" : 83 }
 

The following aggregation operation has two stages:

  1. The $match stage excludes documents that have a score value of less than or equal to 80 to pass along the documents with score greater than 80 to the next stage.

  2. The $count stage returns a count of the remaining documents in the aggregation pipeline and assigns the value to a field called passing_scores.

db.scores.aggregate(
[
{
$match: {
score: {
$gt: 80
}
}
},
{
$count: "passing_scores"
}
]
)
 

The operation returns the following results:

{ "passing_scores" : 4 }
posted @   功夫 熊猫  阅读(14)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架
历史上的今天:
2015-08-12 美国L1签证申请的常见问题解析
2015-08-12 美国L1签证面谈的时候一般VO会问到什么问题?
2015-08-12 美国L-1A签证简介
2015-08-12 想去美国?看完会成功率飙升的美国签证面试技巧
2015-08-12 程序员面试揭秘之程序员靠什么途径去美国工作?
2015-08-12 国签证面试时的注意事项
2015-08-12 nearly,about,almost的区别
点击右上角即可分享
微信分享提示