《MongoDB入门教程》第24篇 聚合统计之$count表达式

Posted 不剪发的Tony老师

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了《MongoDB入门教程》第24篇 聚合统计之$count表达式相关的知识,希望对你有一定的参考价值。

本文将会介绍 $count 表达式,它可以返回一组文档的数量。

$count 表达式

MongoDB $count 表达式的作用就是返回文档的数量,语法如下:

 $count:  

$count 表达式不需要任何参数。

$count 表达式等价于以下形式的 $sum 表达式:

 $sum: 1 

$count 示例

接下来我们将会使用以下集合进行演示:

db.sales.insertMany([
	 "_id" : 1, "item" : "Americanos", "price" : 5, "size": "Short", "quantity" : 22, "date" : ISODate("2022-01-15T08:00:00Z") ,
	 "_id" : 2, "item" : "Cappuccino", "price" : 6, "size": "Short","quantity" : 12, "date" : ISODate("2022-01-16T09:00:00Z") ,
	 "_id" : 3, "item" : "Lattes", "price" : 15, "size": "Grande","quantity" : 25, "date" : ISODate("2022-01-16T09:05:00Z") ,
	 "_id" : 4, "item" : "Mochas", "price" : 25,"size": "Tall", "quantity" : 11, "date" : ISODate("2022-02-17T08:00:00Z") ,
	 "_id" : 5, "item" : "Americanos", "price" : 10, "size": "Grande","quantity" : 12, "date" : ISODate("2022-02-18T21:06:00Z") ,
	 "_id" : 6, "item" : "Cappuccino", "price" : 7, "size": "Tall","quantity" : 20, "date" : ISODate("2022-02-20T10:07:00Z") ,
	 "_id" : 7, "item" : "Lattes", "price" : 25,"size": "Tall", "quantity" : 30, "date" : ISODate("2022-02-21T10:08:00Z") ,
	 "_id" : 8, "item" : "Americanos", "price" : 10, "size": "Grande","quantity" : 21, "date" : ISODate("2022-02-22T14:09:00Z") ,
	 "_id" : 9, "item" : "Cappuccino", "price" : 10, "size": "Grande","quantity" : 17, "date" : ISODate("2022-02-23T14:09:00Z") ,
	 "_id" : 10, "item" : "Americanos", "price" : 8, "size": "Tall","quantity" : 15, "date" : ISODate("2022-02-25T14:09:00Z")
]);

示例一:分组统计文档的数量

以下示例使用 $count 表达式计算不同种类咖啡的数量:

db.sales.aggregate([
  
    $group: 
      _id: '$item',
      itemCount:  $count:  ,
    ,
  ,
])

返回结果如下:

[
   _id: 'Mochas', itemCount: 1 ,
   _id: 'Americanos', itemCount: 4 ,
   _id: 'Lattes', itemCount: 2 ,
   _id: 'Cappuccino', itemCount: 3 
]

其中,

  • _id: “$item” 用于将文档按照 item 字段进行分组,返回 4 个组;
  • $count: 用于统计每个分组内的文档数据,并将结果赋予 itemCount 字段。

示例二:统计与过滤

以下示例使用 $count 表达式计算不同种类咖啡的数量,并且返回数量大于 2 的结果:

db.sales.aggregate([
  
    $group: 
      _id: '$item',
      itemCount:  $count:  ,
    ,
  ,
  
    $match:  itemCount:  $gt: 2  ,
  ,
]);

返回结果如下:

[
   _id: 'Americanos', itemCount: 4 ,
   _id: 'Cappuccino', itemCount: 3 
]

以上是关于《MongoDB入门教程》第24篇 聚合统计之$count表达式的主要内容,如果未能解决你的问题,请参考以下文章

《MongoDB入门教程》第23篇 聚合统计之$sum表达式

《MongoDB入门教程》第25篇 聚合统计之$avg表达式

《MongoDB入门教程》第26篇 聚合统计之$max/$min表达式

《MongoDB入门教程》第22篇 聚合操作

《MongoDB入门教程》第22篇 聚合操作

《MongoDB入门教程》第22篇 聚合操作