Grouping the array items in MongoDB and get the count the products with similar price?

To group array items in MongoDB and count products with similar prices, use the $unwind operator to flatten the array, then $group by price and $sum to count occurrences.

Syntax

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

Sample Data

db.products.insertOne({
    "ProductInformation": [
        {
            "ProductName": "Product-1",
            "ProductPrice": 100
        },
        {
            "ProductName": "Product-2", 
            "ProductPrice": 1100
        },
        {
            "ProductName": "Product-3",
            "ProductPrice": 100
        },
        {
            "ProductName": "Product-4",
            "ProductPrice": 1100
        },
        {
            "ProductName": "Product-5",
            "ProductPrice": 100
        }
    ]
});
{
    "acknowledged": true,
    "insertedId": ObjectId("5e908e2339cfeaaf0b97b57a")
}

Verify Sample Data

db.products.find();
{
    "_id": ObjectId("5e908e2339cfeaaf0b97b57a"),
    "ProductInformation": [
        { "ProductName": "Product-1", "ProductPrice": 100 },
        { "ProductName": "Product-2", "ProductPrice": 1100 },
        { "ProductName": "Product-3", "ProductPrice": 100 },
        { "ProductName": "Product-4", "ProductPrice": 1100 },
        { "ProductName": "Product-5", "ProductPrice": 100 }
    ]
}

Group Array Items by Price

db.products.aggregate([
    {
        "$unwind": "$ProductInformation"
    },
    {
        "$group": {
            "_id": "$ProductInformation.ProductPrice",
            "count": { "$sum": 1 }
        }
    },
    { "$sort": { "_id": 1 } }
]);
{ "_id": 100, "count": 3 }
{ "_id": 1100, "count": 2 }

How It Works

  • $unwind converts each array element into a separate document
  • $group groups documents by ProductPrice and counts using $sum: 1
  • $sort orders results by price in ascending order

Conclusion

Use $unwind to flatten arrays, then $group with $sum: 1 to count items with similar values. This aggregation pipeline effectively groups and counts products by price.

Updated on: 2026-03-15T03:36:03+05:30

975 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements