简体   繁体   English

Java驱动程序MongoDB更新

[英]Java Driver MongoDB updateone

I have a class MongoDAO which has the below code for basic Mongo CRUD operations. 我有一个MongoDAO类,其中包含以下用于基本Mongo CRUD操作的代码。 The line in the code where I am using collection.updateOne method is not compiling and throwing the error " The method updateOne(Bson, Bson) in the type MongoCollection is not applicable for the arguments (Document) ". 我正在使用collection.updateOne方法的代码中的行未编译并引发错误“ MongoCollection类型的updateOne(Bson,Bson)方法不适用于参数(Document) ”。 I need to pass an object of type ToolThing and use the object to update an existing document on mongodb. 我需要传递ToolThing类型的对象,并使用该对象更新mongodb上的现有文档。 How do I resolve this without having to refer to individual parameters of the object ToolThing ? 如何解决此问题而不必引用对象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();
    }

}

Yes you will be getting that exception, Since MongoCollection.updateOne should have two parameters, first parameter is the condition to find the document which need to be updated and the second parameter is the actual update. 是的,您将收到该异常,因为MongoCollection.updateOne应该具有两个参数,第一个参数是查找需要更新的文档的条件,第二个参数是实际更新。

Refer the examples given in the below posts. 请参阅以下帖子中给出的示例。

https://docs.mongodb.com/getting-started/java/update/ https://docs.mongodb.com/getting-started/java/update/

MongoDB update using Java 3 driver 使用Java 3驱动程序更新MongoDB

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM