2013-05-12 55 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