count

The `count` command is used to count the number of documents in a collection that match specific criteria.

This command is useful for obtaining quick statistics about the data stored in your collections, such as the number of documents that meet certain criteria.

Syntax

db.collection.count(
  <query>,
  <options>
);

Parameters

queryobjectrequired

A document specifying the selection criteria using query operators.

optionsobject

A document specifying options including, but not limited to `limit` and `skip`.

Examples

Sample Data

[
  {
    "_id": "00000000-0000-0000-0000-000000003001",
    "name": "Proseware, Inc. | Home Entertainment Hub - East Linwoodbury",
    "promotionEvents": [
      {
        "eventName": "Unbeatable Bargain Bash"
      },
      {
        "eventName": "Steal of a Deal Days"
      }
    ]
  },
  {
    "_id": "00000000-0000-0000-0000-000000003002",
    "name": "Fabrikam, Inc. | Home Accessory Outlet - West Adele",
    "promotionEvents": [
      {
        "eventName": "Incredible Discount Days"
      },
      {
        "eventName": "Steal of a Deal Days"
      }
    ],
    "location": {
      "lat": -89.2384,
      "lon": -46.4012
    }
  },
  {
    "_id": "00000000-0000-0000-0000-000000003003",
    "name": "Wide World Importers | Fitness Equipment Outlet - Reillyborough",
    "promotionEvents": [
      {
        "eventName": "Incredible Discount Days"
      }
    ],
    "location": {
      "lat": -2.4111,
      "lon": 72.1041
    }
  }
]

Counting all documents in a collection

Use the `count` command with an empty document to count **all** documents in a collection.

In this example, all documents in the `stores` collection are counted.

Query:

db.stores.count({ "_id": "00000000-0000-0000-0000-000000003002" })

Output:

1

Counting documents that match nested criteria

The `query` parameter supports nested parameters.

In this example, the command counts documents that match the string value `"Incredible Discount Days"` for the `promotionEvents.eventName` field.

Query:

db.stores.count({ "promotionEvents.eventName": "Incredible Discount Days" })

Output:

2

Counting documents that match multiple criteria

The `query` parameter also supports multiple parameters.

In this example, the `locationLatitude` and `locationLongitude` parameters are used to count documents that match on these specific values.

Query:

db.stores.count({ "location.lat": -2.4111, "location.lon": 72.1041 })

Output:

1

Related