Matan L
Matan L

Reputation: 1027

MongoDB java update a doument by a function with fields

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

Answers (1)

Parvin Gasimzade
Parvin Gasimzade

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 :

  1. Get current object.
  2. If it is null calculate average_cost & total_items and insert into DB.
  3. If it is not null, get current total_items & average_cost field.
  4. Calculate new total_items & average_cost values.
  5. Update those fields using $set query parameter.

Upvotes: 1

Related Questions