Search code examples
mongodbmongodb-queryaggregation-frameworknosql-aggregation

how to group array value with count in mongodb?


I've got a collection like this:

{
  "_id": ObjectID(1),
  "fruits": [Banana, Banana, Apple]
}
{
  "_id": ObjectID(2),
  "fruits": [Apple]
}

I want to get the count of the array data, like 2 Banana and 1 Apple for the first object; 1 Apple for the second object.

How can i do this?


Solution

    1. $unwind - Deconstruct fruits array into multiple documents.

    2. $group - Group by _id and fruits. Perform count.

    3. $group - Group by _id._id. Push object into fruits array.

    4. $set - Set fruits to key-value pair.

    db.collection.aggregate([
      {
        $unwind: "$fruits"
      },
      {
        $group: {
          _id: {
            _id: "$_id",
            fruit: "$fruits"
          },
          count: {
            $sum: 1
          }
        }
      },
      {
        $group: {
          _id: "$_id._id",
          fruits: {
            $push: {
              k: "$_id.fruit",
              v: "$count"
            }
          }
        }
      },
      {
        $set: {
          fruits: {
            $arrayToObject: "$fruits"
          }
        }
      }
    ])
    

    Sample Mongo Playground

    Output

    [
      {
        "_id": 2,
        "fruits": {
          "Apple": 1
        }
      },
      {
        "_id": 1,
        "fruits": {
          "Apple": 1,
          "Banana": 2
        }
      }
    ]