MongoDB Sum When the field is a string string type (go language)

Aggregation (aggregate) in MongoDB is mainly used to process data (such as statistical average, summation, etc.) and return the calculated data results.

If the value of price is long/int

{ "_id" : 1, "price" : 10 }

{ "_id" : 2, "price" : 20 }

{ "_id" : 3, "price" : 30 }

As in the above orders table, the sum of prices needs to be counted

When summing data, if the sum field is NumberLong type or Integer type direct aggregation function can be done

db.orders.aggregate([ 
    { 
        $group:{ 
            _id:null, 
            total:{$sum: '$price'} 
        } 
    } 
])

 The final result is: { "_id" : null, "total" : 60 }

If the value of price is string

{ "_id" : 1, "price" : "10" }

{ "_id" : 2, "price" : "20" }

{ "_id" : 3, "price" : "30" }

As in the above orders table, the sum of prices needs to be counted

When summing data, if you want the sum field to be of string type, you need to perform type conversion through the aggregate function " $toDouble " . For the usage method, see

db.orders.aggregate([
    {
        $group:{ 
            _id:null, 
            total:{
                 $sum: {
                    $toDouble:'$price'
                 }
            }
        } 
    } 
])

Guess you like

Origin blog.csdn.net/qq_48626761/article/details/125970470