Skip to content

DOCS-8144: $count aggregation stage #2763

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions source/includes/ref-toc-aggregation-pipeline-operator.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -119,4 +119,10 @@ description: |
operation replaces all existing fields in the input document,
including the ``_id`` field. Specify a document embedded in the
input document to promote the embedded document to the top level.
---
name: :pipeline:`$count`
file: /reference/operator/aggregation/count
description: |
Returns a count of the number of documents at this stage of the
aggregation pipeline.
...
75 changes: 75 additions & 0 deletions source/reference/operator/aggregation/count.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
====================
$count (aggregation)
====================

.. default-domain:: mongodb

.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol

Definition
----------

.. expression:: $count

Returns a document containing a count of the number of
documents input to the stage.

:expression:`$count` has the following prototype form:

.. code-block:: javascript

{ $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.

Example
-------

A collection named ``scores`` has the following documents:

.. code-block:: javascript

{ "_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 aggregration operation has two stages:

#. The :expression:`$match` stage excludes documents which have a
``score`` value of less than ``80``

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

.. code-block:: javascript

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

The operation returns the following results:

.. code-block:: javascript

{ "passing_scores" : 4 }