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 :

  1. get current object.
  2. if null calculate average_cost & total_items , insert db.
  3. if not null, current total_items & average_cost field.
  4. calculate new total_items & average_cost values.
  5. update fields using $set query parameter.

Comments

Popular posts from this blog

c# - DetailsView in ASP.Net - How to add another column on the side/add a control in each row? -

javascript - firefox memory leak -

Trying to import CSV file to a SQL Server database using asp.net and c# - can't find what I'm missing -