How to use count in group in MongoDB?

alerts.aggregate([{
            $match: {
                "misc.createdTime": {
                    $gt: new Date(weekStart) // 7 days ago
                },
                alertState: alertState,
                alertCategory: {'$regex': alertCategory}
            }
        },
        {
            $group: {
                _id: {
                    $dateToString: {
                        format: "%Y%m%d",
                        date: "$misc.createdTime"
                    }
                },
                count: { $sum: { $cond: [ { $eq: [ "$match", "none" ] }, 0, 1 ] } } // => based on another SO answer, but doesn't seem to work.
                // count: {
                //     $sum: 1
                // }
            }
        },
        {
            $sort: {
                _id: 1
            }
        }
    ]).toArray();

Summary: in this tutorial, you’ll learn how to use the MongoDB $count to return the number of documents in a group.

Introduction to the MongoDB $count

MongoDB $count returns the number of documents in a group. Here’s the syntax of the $count:

{ $count: {} }

Code language: PHP (php)

Note that the $count does not accept any parameters.

The $count is functionally equivalent to using the following

{ $sum: 1 }

Code language: PHP (php)
2 in the

{ $sum: 1 }

Code language: PHP (php)
3 stage:

{ $sum: 1 }

Code language: PHP (php)

MongoDB $count examples

We’ll use the following

{ $sum: 1 }

Code language: PHP (php)
4 collection to demonstrate the $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")} ]);

Code language: JavaScript (javascript)

1) Using MongoDB $count to count the number of documents per group example

The following example uses the $count to calculate the number of documents per item and returns the item with a count greater than two:

How to use group and count in MongoDB?

We can use the following code to group by the 'position' field and count the occurrences of each position..
The position 'Forward' occurs 1 time..
The position 'Guard' occurs 3 times..
The position 'Center' occurs 1 time..

How to use count in MongoDB?

When performing a count, MongoDB can return the count using only the index if:.
the query can use an index,.
the query only contains conditions on the keys of the index, and..
the query predicates access a single contiguous range of index keys..

How to get document count in MongoDB aggregation?

You can use $facet that enables you do execute multiple aggregation pipelines on the same set of documents. You can both count the total documents and return pagination results, all in one query.

How do I count the number of records in MongoDB?

MongoDB count() Method – db. Collection. count() The count() method counts the number of documents that match the selection criteria.