Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

multiply in mongodb saying operation only on string type

I am trying to multiply 2 fields in mongodb. Both are of numeric type, but mongodb is returning $multiply only supports numeric types. The collection is:

{
        "_id" : ObjectId("55e07eb54acc499bb3daae6a"),
        "propertytype" : "Hotel",
        "name" : "Rude Lounge2",
        "costing" : {
                "vegperplate" : 350,
                "nonvegperplate" : 450,
                "flatcharge" : 20000
        },
        "capacity" : {
                "min" : 90,
                "max" : 200
        }
}
{
        "_id" : ObjectId("55e07ebe4acc499bb3daae6b"),
        "propertytype" : "Hotel",
        "name" : "Rude Lounge3",
        "costing" : {
                "vegperplate" : 350,
                "nonvegperplate" : 450,
                "flatcharge" : 20000
        },
        "capacity" : {
                "min" : 90,
                "max" : 200
        }
}

My query is :

> db.properties2.aggregate(
... { $project: {
...  "cost": {
... $multiply:["costing.vegperplate","capacity.min"]
...       }
... }
... })

Error stack is:

assert: command failed: {
        "errmsg" : "exception: $multiply only supports numeric types, not String",
        "code" : 16555,
        "ok" : 0
} : aggregate failed
Error: command failed: {
        "errmsg" : "exception: $multiply only supports numeric types, not String",
        "code" : 16555,
        "ok" : 0
} : aggregate failed
    at Error (<anonymous>)
    at doassert (src/mongo/shell/assert.js:11:14)
    at Function.assert.commandWorked (src/mongo/shell/assert.js:244:5)
    at DBCollection.aggregate (src/mongo/shell/collection.js:1149:12)
    at (shell):1:16
2015-08-29T00:13:39.173-0400 Error: command failed: {
        "errmsg" : "exception: $multiply only supports numeric types, not String",
        "code" : 16555,
        "ok" : 0
} : aggregate failed at src/mongo/shell/assert.js:13

Anybody where am I doing wrong?

like image 562
Satya Avatar asked Dec 05 '25 02:12

Satya


2 Answers

You need to prefix your fields' name with the $ sign since your operation is in on two different fields in your document.

db.properties2.aggregate([
    { 
        "$project": {
            "cost": { "$multiply": [ "$costing.vegperplate", "$capacity.min" ]}
    }
])
like image 58
styvane Avatar answered Dec 06 '25 15:12

styvane


The parameters specified inside $multiply:[] should be int. IF a string is there. convert it to string by

$multiply:['$quantity',{$toInt:'$product.prize'}]

toInt converts your string argument to int

like image 20
Adarsh S Kumar Avatar answered Dec 06 '25 17:12

Adarsh S Kumar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!