简体   繁体   中英

Java Driver MongoDB updateone

I have a class MongoDAO which has the below code for basic Mongo CRUD operations. 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) ". I need to pass an object of type ToolThing and use the object to update an existing document on mongodb. How do I resolve this without having to refer to individual parameters of the object 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.

Refer the examples given in the below posts.

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

MongoDB update using Java 3 driver

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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