22

I am trying to update at once multiple fields in a single MongoDB document, but only one field is updated. I have a collection user, in which users are uniquely defined by a customer_user_id. I want to update a certain user's birth_year and country fields.

This is what I am doing:

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

Unfortunately, only the country field is updated, and the logged updateQuery looks like this:

Update query: { "$set" : { "country" : "Austria"}}

4 Answers 4

24

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));
Sign up to request clarification or add additional context in comments.

1 Comment

@wawek, I'm trying your approach and none of the document's field is not updated. I'm querying the documents by _id, which exist and trying to push an update of the specific fields but nothing happens. Code: 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);
17

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.

3 Comments

According to docs, updateMany updates all documents, not multiple fields in a single MongoDB document.
Hi @Half_Duplex, can you justify your statement by giving proper example. Also can you share the MongoDB doc link which contains this statement. Thanks
Does combine create an aggregation pipeline or a normal / traditional update (i.e. a single set statement?
8

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

2 Comments

Yeah.. this is the new way.
The new way is not using new Document("$set", new Document("fieldA", "valueA")). The new way is to use com.mongodb.client.model.Updates as answered by @pakat
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.