16

I'm switching to the MongoDB Java driver version 3. I cannot figure out how to perform an update of a Document. For example, I want to change the "age" of an user:

MongoDatabase db = mongoClient.getDatabase("exampledb");
MongoCollection<org.bson.Document> coll = db.getCollection("collusers");

Document doc1 = new Document("name", "frank").append("age", 55) .append("phone", "123-456-789");
Document doc2 = new Document("name", "frank").append("age", 33) .append("phone", "123-456-789");
coll.updateOne(doc1, doc2); 

The output is:

java.lang.IllegalArgumentException: Invalid BSON field name name

Any idea how to fix it ? Thanks!

3 Answers 3

41

Use:

coll.updateOne(eq("name", "frank"), new Document("$set", new Document("age", 33)));

for updating the first Document found. For multiple updates:

coll.updateMany(eq("name", "frank"), new Document("$set", new Document("age", 33)));

On this link, you can fine a quick reference to MongoDB Java 3 Driver

Sign up to request clarification or add additional context in comments.

4 Comments

What what what??? $set is Jiffa!!! Who thought of this implicit/hidden directive? What does it actually mean in comparison to other i don't know implicit/hidden directives?
@AlikElzin-kilaka, I don't know what "Jiffa" means but I certain we're very much in agreement about the crazy way in which the set command is passed to the server. The driver should have wrapped $set, $inc etc.
@Paul Japan International Freight Forwarders Association, Inc, apparently.
how can this be achieved with helper functions? eq(...), set(new Document("age",33)) does not seem to work for some reason
11

in Mongodb Java driver 3.0 , when you update a document, you can call the coll.replaceOne method to replace document, or call the coll.updateOne / coll.updateMany method to update document(s) by using $set/$setOnInsert/etc operators.

in your case, you can try:

coll.updateOne(eq("name", "frank"), new Document("$set", new Document("age", 33)));
coll.replaceOne(eq("name", "frank"), new Document("age", 33));

Comments

1

You can try this

coll.findOneAndReplace(doc1, doc2);

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.