我正在切换到MongoDB Java driver版本3。我不知道如何执行文档更新。例如,我想要更改用户的“年龄”:
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);
输出为:
java.lang.IllegalArgumentException: Invalid BSON field name name
你知道怎么修复它吗?谢谢!
发布于 2015-04-04 21:16:18
使用:
coll.updateOne(eq("name", "frank"), new Document("$set", new Document("age", 33)));
用于更新找到的第一个文档。对于多个更新:
coll.updateMany(eq("name", "frank"), new Document("$set", new Document("age", 33)));
在此链接上,您可以查找一个quick reference to MongoDB Java 3 Driver
发布于 2015-05-26 11:58:11
在Mongodb Java driver 3.0中,当您更新文档时,您可以调用coll.replaceOne方法来替换文档,或者通过使用$set/$setOnInsert/etc运算符调用coll.updateOne / coll.updateMany方法来更新文档。
在您的情况下,您可以尝试:
coll.updateOne(eq("name", "frank"), new Document("$set", new Document("age", 33)));
coll.replaceOne(eq("name", "frank"), new Document("age", 33));
发布于 2015-04-04 04:52:31
你可以试试这个
coll.findOneAndReplace(doc1, doc2);
https://stackoverflow.com/questions/29434207
复制相似问题