Reputation: 101
I'm trying to do the equivalent of
UPDATE TABLENAME SET COLUMN = COLUMN * 0.725
in mongodb.
Here is what I tried but doesn't seem to work. Help!
db.costs.update(
{$mul: {totalcost: NumberDecimal("0.725")}},
{multi: true}
);
generates
"errmsg" : "unknown top level operator: $mul"
and the below
db.costs.update(
{ recordId: {$regex:"*"}},
{$mul: {totalcost: NumberDecimal("0.725")}},
{multi: true}
);
generates
"errmsg" : "Regular expression is invalid: nothing to repeat"
Apparently I'm missing the syntax and scoured through the documentation but couldn't find anything that could help.
thanks
Upvotes: 0
Views: 250
Reputation: 114
Edited. Looks like you are trying to do a bulk update.
var bulk = db.getCollection('collection-name').initializeUnorderedBulkOp()
bulk.find({}).update({ $mul : {points: 2}}); // will multiply the field by 2
bulk.execute();
There is should work. For more info, check out unordered and ordered operations.
Upvotes: 0
Reputation: 3010
The following query can get us the expected output:
db.collection.updateMany({},
{
$mul:{
"totalCost": 0.725
}
})
Data set:
{ "_id" : ObjectId("5d882f0d38db7cf8d3f75cdd"), "totalCost" : 1000 }
{ "_id" : ObjectId("5d882f0d38db7cf8d3f75cde"), "totalCost" : 1200 }
{ "_id" : ObjectId("5d882f0d38db7cf8d3f75cdf"), "totalCost" : 1500 }
{ "_id" : ObjectId("5d882f0d38db7cf8d3f75ce0"), "totalCost" : 1800 }
Output:
{ "_id" : ObjectId("5d882f0d38db7cf8d3f75cdd"), "totalCost" : 725 }
{ "_id" : ObjectId("5d882f0d38db7cf8d3f75cde"), "totalCost" : 870 }
{ "_id" : ObjectId("5d882f0d38db7cf8d3f75cdf"), "totalCost" : 1087.5 }
{ "_id" : ObjectId("5d882f0d38db7cf8d3f75ce0"), "totalCost" : 1305 }
Upvotes: 1