Подтвердить что ты не робот

Java + MongoDB: обновление нескольких полей в документе

Я пытаюсь обновить сразу несколько полей в одном документе MongoDB, но обновляется только одно поле. У меня есть коллекция пользователь, в которой пользователи уникально определены customer_user_id. Я хочу обновить определенные поля birth_year и страны.

Это то, что я делаю:

// 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 выглядит следующим образом:

Обновить запрос: { "$ set": { "страна": "Австрия" }}

4b9b3361

Ответ 1

Я не могу проверить это, но, возможно, вам стоит попробовать:

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

Ответ 2

Для 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);