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!
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
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));
You can try this
coll.findOneAndReplace(doc1, doc2);
来源:https://stackoverflow.com/questions/29434207/mongodb-update-using-java-3-driver