Java + MongoDB: Updating multiple fields in a document

For MongoDB 3.4 you can use

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

Alternatively, there are convenience methods in com.mongodb.client.model.Updates to do this:

MongoCollection<Document> collection = mongoClient.getDatabase("db").getCollection("user");

collection.updateMany(
    Filters.eq("customer_user_id", customer_user_id),
    Updates.combine(
        Updates.set("birth_year", birth_year),
        Updates.set("country", country)
    ));

Underlying this will create a Bson query with $set as well, but using convenience methods keeps your code more clear and readable.


I cannot verify that but maybe you should try:

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

or this is pretty the same I think:

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

A variation on answer by @pakat...

MongoCollection<Document> collection = mongoClient.getDatabase("db").getCollection("user");

List<Bson> updatePredicates = new ArrayList<Bson>();
Bson predicateBirthYear = set("birth_year", birth_year);
Bson predicateCountry = set("country", country);

updatePredicates.add(predicateBirthYear);
updatePredicates.add(predicateCountry);

collection.updateMany(Filters.eq("customer_user_id", customer_user_id), Updates.combine(updatePredicates));

Tags:

Java

Mongodb