我有一个 MongoDAO 类,它具有以下用于基本 Mongo CRUD 操作的代码。我使用 collection.updateOne 方法的代码行未编译并抛出错误“MongoCollection 类型中的方法 updateOne(Bson, Bson) 不适用于参数(文档)” 。我需要传递 ToolThing 类型的对象并使用该对象更新 mongodb 上的现有文档。如何解决此问题,而无需引用对象 ToolThing 的各个参数?
private String mongoDB;
private String mongoCollection;
private List<ToolThing> tools;
private ToolThing tool;
MongoClient mongoClient = new MongoClient();
MongoDatabase db = mongoClient.getDatabase("test");
MongoCollection collection = db.getCollection("tools");
public void updateOne(ToolThing input){
try {
JSONObject jsonObject = new JSONObject(input);
String inputJson = jsonObject.toString();
Document inpDoc = Document.parse(inputJson);
collection.updateOne(new Document(inpDoc));
} catch (Exception e) {
System.out.println("Mongo Deletion operation failed");
e.printStackTrace();
}
}
最佳答案
是的,你会得到这个异常,因为 MongoCollection.updateOne 应该有两个参数,第一个参数是查找需要更新的文档的条件,第二个参数是实际更新。
请参阅以下帖子中给出的示例。
关于Java 驱动程序 MongoDB updateone,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38710137/