mongodb Aggregation聚合操作之$count

在上一篇 mongodb Aggregation聚合操作之$unwind 中详细介绍了mongodb聚合操作中的$unwind使用以及参数细节。本篇将开始介绍Aggregation聚合操作中的$count操作。

说明:

查询展示文档数量的总数。

语法:

{ $count: }

1. 示例


初始化数据:

 db.scores.insertMany([{ "_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 }])


示例:

db.scores.aggregate(

  [

    {

      $match: {

        score: {

          $gt: 80

        }

      }

    },

    {

      $count: "passing_scores"

    }

  ]

)

等同于:

db.scores.countDocuments({"score":{$gt:80}})

结果:

{

    "passing_scores" : 4

}

你可能感兴趣的:(mongodb Aggregation聚合操作之$count)