How to calculate sum of string in MongoDB?

To calculate sum of string values in MongoDB, use the aggregate pipeline with $group and $sum operators. Convert string numbers to integers using $toInt before summing them.

Syntax

db.collection.aggregate([
    {
        $group: {
            _id: null,
            totalSum: {
                $sum: { $toInt: "$fieldName" }
            }
        }
    }
]);

Create Sample Data

db.demo71.insertMany([
    { "Price": "20" },
    { "Price": "50" },
    { "Price": "20" },
    { "Price": "10" }
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5e29af210912fae76b13d76e"),
        ObjectId("5e29af240912fae76b13d76f"),
        ObjectId("5e29af270912fae76b13d770"),
        ObjectId("5e29af2d0912fae76b13d771")
    ]
}

Display Sample Data

db.demo71.find();
{ "_id": ObjectId("5e29af210912fae76b13d76e"), "Price": "20" }
{ "_id": ObjectId("5e29af240912fae76b13d76f"), "Price": "50" }
{ "_id": ObjectId("5e29af270912fae76b13d770"), "Price": "20" }
{ "_id": ObjectId("5e29af2d0912fae76b13d771"), "Price": "10" }

Calculate Sum of String Values

db.demo71.aggregate([
    {
        $group: {
            _id: null,
            TotalPrice: {
                $sum: {
                    $toInt: "$Price"
                }
            }
        }
    }
]);
{ "_id": null, "TotalPrice": 100 }

How It Works

  • $group − Groups all documents together with _id: null
  • $toInt − Converts string values to integers
  • $sum − Calculates the total sum of converted integers

Conclusion

Use $toInt within $sum to convert string numbers to integers before aggregation. This approach efficiently calculates the total sum of numeric string fields across all documents in the collection.

Updated on: 2026-03-15T01:50:01+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements