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"}}
To update a single field or specific fields just use the $set operator. This will update a specific field of "citiName" by value "Jakarta Pusat" that defined by $set operator.
The way we do this is by $project ing our documents and using the $concat string aggregation operator to return the concatenated string. You then iterate the cursor and use the $set update operator to add the new field to your documents using bulk operations for maximum efficiency.
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));
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With