MongoDB java update a doument by a function with fields -
i using mongodb, java, have following document structure :
{ _id : ... total_items : 34 avarage_cost : 54 }
now have item cost, , want update collection total increase 1 , avarage cost right, best way so?
i thought doing :
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 good/working solution ? best way ?
for cannot run javascript code on update queries. there open issue on jira. check issue here.
you can solve problem follows :
- get current object.
- if null calculate average_cost & total_items , insert db.
- if not null, current total_items & average_cost field.
- calculate new total_items & average_cost values.
- update fields using
$set
query parameter.
Comments
Post a Comment