2014-04-17 64 views
0

我正在嘗試使用對象ID更新文檔,但沒有收到結果。這裏是我的代碼請幫我我們可以使用_id在java中更新mongodb中的文檔嗎?

DBCollection patients= db.getCollection("Patients"); 
    BasicDBObject doc = new BasicDBObject(); 
      doc.put("name","seshu"); 


DBObject update=`new` BasicDBObject().append("_id",ObjectId("534e1c8e40a8af540cd01ff4")); 

    patients`enter code here`.update(update, doc); 

回答

1

當你說「沒有得到結果」,我假定你的意思是文件沒有被更新?

您確定您的集合名稱,數據庫名稱和ObjectId正確嗎?並且該文檔以該ObjectId存在於該集合中。你應該通過你的程序或者mongo shell來檢查所有這些。

你爲什麼不也嘗試加入一些額外的檢查/調試你的代碼,這樣的事情:

DBCollection patients = db.getCollection("Patients"); 
DBObject update = new BasicDBObject().append("_id", new ObjectId("...")); 

long collectionCount = patients.count(); 
System.out.println(String.format("Collection count: %s", collectionCount)); 
long count = patients.count(update); 
System.out.println(String.format("Count for query: %s", count)); 

BasicDBObject doc = new BasicDBObject(); 
doc.put("name", "seshu"); 


WriteResult writeResult = patients.update(update, doc); 
System.out.println(String.format("Updated %s records", writeResult.getN())); 

DBObject updated = patients.findOne(update); 
System.out.println(updated); 
相關問題