2015-10-29 76 views
11

我試圖一次更新單個MongoDB文檔中的多個字段,但只更新一個字段。 我有一個集合用戶,其中用戶由customer_user_id唯一定義。我想更新某個用戶的birth_year國家字段。Java + MongoDB:更新文檔中的多個字段

這是我在做什麼:

// Define the search query: 
DBCollection col = md.getDb().getCollection("user"); 
BasicDBObject searchQuery = new BasicDBObject("customer_user_id", customer_user_id); 

// Define the update query: 
BasicDBObject updateQuery = new BasicDBObject(); 
updateQuery.append("$set", new BasicDBObject().append("birth_year", birth_year); 
updateQuery.append("$set", new BasicDBObject().append("country", country); 

log.info("Update query: " + updateQuery); 
col.update(searchQuery, updateQuery); 

遺憾的是,只有國家字段更新,和登錄updateQuery看起來是這樣的:

更新查詢:{「$集「:{」country「:」Austria「}}

回答

12

我無法驗證,但也許你應該嘗試:

BasicDBObject updateFields = new BasicDBObject(); 
updateFields.append("birth_year", birth_year); 
updateFields.append("country", country); 
BasicDBObject setQuery = new BasicDBObject(); 
setQuery.append("$set", updateFields); 
col.update(searchQuery, setQuery); 

或這是很相同,我認爲:

updateQuery.put("$set", new BasicDBObject("country",country).append("birth_year", birth_year)); 
+0

@wawek,我想你的文檔的領域的做法,並沒有沒有更新。我用'_id'查詢文件,它存在並試圖推送特定字段的更新,但沒有任何反應。 代碼:'BasicDBObject searchQry = new BasicDBObject(「_ id」,epID); BasicDBObject updateFields = new BasicDBObject(); updateFields.append(「isExpired」,true); updateFields.append(「fetchStatus」,FetchStatus.FETCHED.getID()); BasicDBObject setQuery = new BasicDBObject(); setQuery.append(「$ set」,updateFields); UpdateResult updRes = dbC_Episodes.updateOne(searchQry,setQuery);' –

1

MongoDB的3.4可以使用

MongoCollection<Document> collection = database.getCollection(nameOfCollection); 
Bson filter = new Document("SearchKey", Value); 
Bson newValue = new Document("UpdateKey1", "Value1").append("UpdateKey2", "Value2")....;  
Bson updateOperationDocument = new Document("$set", newValue); 
collection.updateMany(filter, updateOperationDocument); 
+0

是的..這是新的方法。 – FaithReaper

相關問題