MongoDB update using Java 3 driver

2019-02-04 10:53发布

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条回答
来,给爷笑一个
2楼-- · 2019-02-04 11:18

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));
查看更多
\"骚年 ilove
3楼-- · 2019-02-04 11:18

You can try this

coll.findOneAndReplace(doc1, doc2);
查看更多
男人必须洒脱
4楼-- · 2019-02-04 11:26

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

查看更多
登录 后发表回答