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!

user2824073
  • 2,407
  • 10
  • 39
  • 73

3 Answers3

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

Francesco Marchioni
  • 4,091
  • 1
  • 25
  • 40
  • 4
    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 Aug 26 '15 at 10:15
  • 1
    @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 Sep 01 '16 at 15:11
  • @Paul Japan International Freight Forwarders Association, Inc, apparently. – Joel Peltonen Nov 03 '16 at 13:41
  • how can this be achieved with helper functions? `eq(...), set(new Document("age",33))` does not seem to work for some reason – phil294 Jun 18 '17 at 19:27
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));
1

You can try this

coll.findOneAndReplace(doc1, doc2);