簡體   English   中英

Java驅動程序MongoDB更新

[英]Java Driver MongoDB updateone

我有一個MongoDAO類,其中包含以下用於基本Mongo CRUD操作的代碼。 我正在使用collection.updateOne方法的代碼中的行未編譯並引發錯誤“ MongoCollection類型的updateOne(Bson,Bson)方法不適用於參數(Document) ”。 我需要傳遞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應該具有兩個參數,第一個參數是查找需要更新的文檔的條件,第二個參數是實際更新。

請參閱以下帖子中給出的示例。

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

使用Java 3驅動程序更新MongoDB

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM