MongoDB query to count the frequency of every element of the array

To count the frequency of every element in an array across all documents in a MongoDB collection, use the aggregation pipeline with $unwind, $group, and $sum operators.

Syntax

db.collection.aggregate([
    { $unwind: "$arrayField" },
    { $group: { _id: "$arrayField", count: { $sum: 1 } } }
]);

Sample Data

db.demo184.insertMany([
    { "Names": ["Chris", "David", "Bob"] },
    { "Names": ["Chris", "Mike"] },
    { "Names": ["Chris", "Bob", "Carol"] }
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5e3999fb9e4f06af55199805"),
        ObjectId("5e399a0d9e4f06af55199806"),
        ObjectId("5e399a209e4f06af55199807")
    ]
}

Method 1: Simple Frequency Count

Count the frequency of each name in the Names array ?

db.demo184.aggregate([
    { $unwind: "$Names" },
    { $group: { _id: "$Names", count: { $sum: 1 } } }
]);
{ "_id": "Mike", "count": 1 }
{ "_id": "Carol", "count": 1 }
{ "_id": "David", "count": 1 }
{ "_id": "Bob", "count": 2 }
{ "_id": "Chris", "count": 3 }

Method 2: Formatted Output as Single Object

Transform the result into a single object with name-count pairs ?

db.demo184.aggregate([
    { $unwind: "$Names" },
    { $group: { _id: "$Names", count: { $sum: 1 } } },
    { $group: {
        _id: null,
        counts: {
            $push: {
                k: "$_id",
                v: "$count"
            }
        }
    } },
    { $replaceRoot: {
        newRoot: { $arrayToObject: "$counts" }
    } }
]);
{ "Carol": 1, "David": 1, "Chris": 3, "Bob": 2, "Mike": 1 }

How It Works

  • $unwind creates separate documents for each array element
  • $group groups by element value and counts occurrences using $sum: 1
  • $arrayToObject converts key-value pairs into a single object format

Conclusion

Use $unwind and $group with $sum to count array element frequencies. For formatted output, combine with $arrayToObject to create a single object with element-count pairs.

Updated on: 2026-03-15T01:40:54+05:30

896 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements