2015-10-29 24 views
11

Sto tentando di aggiornare contemporaneamente più campi in un singolo documento MongoDB, ma viene aggiornato solo un campo. Ho una collezione utente, in cui gli utenti sono definiti in modo univoco da customer_user_id. Desidero aggiornare i campi di un determinato utente birth_year e paese.Java + MongoDB: aggiornamento di più campi in un documento

Questo è quello che sto facendo:

// 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); 

Purtroppo, solo il campo paese viene aggiornato, e l'updateQuery loggato assomiglia a questo:

query di aggiornamento: { "$ set ": {" paese ":" Austria "}}

risposta

12

Non riesco a verificarlo ma forse dovresti provare:

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

o questo è abbastanza lo stesso credo:

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

@wawek, sto cercando il vostro approccio e nessuno di campo del documento non è aggiornato. Sto interrogando i documenti con '_id', che esistono e cercando di spingere un aggiornamento dei campi specifici ma non succede nulla. Codice: '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

Per MongoDB 3.4 è possibile utilizzare

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

Sì .. questo è il nuovo modo. – FaithReaper

Problemi correlati