Reputation: 1027
I am using mongodb, with java, I have the following document structure :
{
_id : ...
total_items : 34
avarage_cost : 54
}
now i have an item with its cost, and i want to update my collection so that the total will increase by 1 and the avarage cost will be right, what would be the best way to do so?
I thought about doing something like this :
int cost = ... ;
BasicDBObject updatequery = new BasicDBObject();
updatequery.put("$inc", BasicDBObjectBuilder.start().add("total_items ", 1).get());
updatequery.put("$function", "function(){this.avarage_cost = ((this.total_items-1)*this.avarage_cost + "+cost+"/) / this.total_items;}");
is this a good/working solution ? what would be the best way to do so ?
Upvotes: 0
Views: 123
Reputation: 26012
For now you cannot run javascript code on update queries. There is an open issue on Jira. Check issue here.
You can solve this problem as follows :
$set
query parameter.Upvotes: 1