2013-05-12 53 views
0

功能更新doument,用java, 我有以下的文档结构:MongoDB的java编写与我使用MongoDB的领域

{ 
    _id : ... 
    total_items : 34 
    avarage_cost : 54 
} 

现在我有成本的项目,我想更新我的收藏,以便总数将增加1,平均成本将是正确的, 这将是最好的方式吗?

我想过做这样的事情:

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;}"); 

这是一个很好的/工作解决方案吗? 最好的办法是什么?

回答

1

现在,您无法在更新查询上运行JavaScript代码。 Jira有一个公开的问题。检查问题here

可以按如下方式解决这个问题:

  1. 获取当前对象。
  2. 如果为空,则计算average_cost & total_items并插入到数据库中。
  3. 如果不为空,则获取当前total_items & average_cost字段。
  4. 计算新的total_items & average_cost值。
  5. 使用$set查询参数更新这些字段。
+0

这是唯一的方法吗?我想避免获取当前对象... – 2013-05-13 15:35:12