MongoDB update using Java 3 driver

拜拜、爱过 提交于 2019-11-29 07:40:32

问题


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!


回答1:


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




回答2:


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



回答3:


You can try this

coll.findOneAndReplace(doc1, doc2);


来源:https://stackoverflow.com/questions/29434207/mongodb-update-using-java-3-driver

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!