2015-10-29 24 views
11

1つのMongoDBドキュメントで複数のフィールドを一度に更新しようとしていますが、1つのフィールドのみが更新されています。 は、私は、ユーザーが独自に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); 

かこれはかなり私が思う同じです:MongoDBの3.4については

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

をあなたは

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

関連する問題