簡體   English   中英

嘗試使用 MongoDB Java 驅動程序更新文檔

[英]Trying to update a document using MongoDB Java Driver

謝謝

  • 我只想感謝您點擊這個問題! 我已盡力使這盡可能徹底。
  • 但是,如果您需要進一步澄清任何事情,請隨時告訴我!
  • 如果你覺得問題太長。 您可以閱讀第三和第四部分並在此處發布您自己的解決方案!

設置

  • Mongodb Java 驅動程序:org.mongodb:mongo-java-driver:3.11.0-rc0

我想做的事

  • 查找具有特定“名稱”字段的特定文檔。
  • 然后更新另一個字段或整個文檔。

示例文檔

// the document that I am trying to find in db
{
  "_id":"5de6af7cfa42833bd9849477",
  "name":"Richard Koba",
  "skills":[]
}

// the document that I have
{
  "name":"Richard Koba",
  "skills":[jump, dance, sing]
}

// final result in db
{
  "_id":"5de6af7cfa42833bd9849477",
  "name":"Richard Koba",
  "skills":[jump, dance, sing]
}

我現在在做什么

  // finding a document with same "name" field as input doc and update it with doc
  public MongoCollection updateDocument(Document doc, String colName) {
    MongoCollection collection;

    // make sure collection exist
    try {
      collection = connectCollection(colName); // returns MongoCollection Obj
    } catch (CollectionNotFoundException e) {
      MessageHandler.errorMessage(e.getMessage());
      return null;
    }

    // trying to find the document.
    if (collection.find(eq("name", doc.get("name"))).first() == null) {
      // if document not found, insert a new one
      collection.insertOne(doc);
    } else {
      // if the document found, replace/update it with the one I have
      collection.replaceOne(eq("name", doc.get("name")), doc);
    }

    return collection;
  }

我發現了什么關於我的錯誤解決方案

  1. collection.find(eq("name", doc.get("name"))).first()從不返回 null。
  2. Java 只告訴我它返回一個對象。 MongoDB 文檔告訴我它是一個TResult ,它指向MongoIterable<TResult> 我被困在這里。
  3. 代碼結果是最后沒有插入/更新任何文檔。

參考

我嘗試了一些代碼,這工作正常。 這與您的代碼沒有太大區別。

mongo shell創建了一個文檔:

MongoDB Enterprise > db.users.findOne()
{
        "_id" : "5de6af7cfa42833bd9849477",
        "name" : "Richard Koba",
        "skills" : [ ]
}

我的Java代碼:

// Test input documents
private Document doc1 = new Document()
                           .append("name", "Richard Koba")
                           .append("skills", Arrays.asList("jump", "dance", "sing"));
private Document doc2 = new Document()
                            .append("name", "Richard K")
                            .append("skills", Arrays.asList("sings"));

doc1傳遞給以下方法時,結果是:“### Doc FOUND”。 並且,對於doc2 ,結果是“### Doc NOT found”。

private void checkDocument(Document doc) {

    MongoClient mongoClient = MongoClients.create("mongodb://localhost/");
    MongoDatabase database = mongoClient.getDatabase("javadb");
    MongoCollection<Document> collection = database.getCollection("users");

    if (collection.find(eq("name", doc.get("name"))).first() == null) {

        System.out.println("### Doc NOT found");
    } 
    else {
        System.out.println("### Doc FOUND");
    }
}

我也試過這個,結果相同。

Document d = collection.find(eq("name", doc.get("name"))).first();
if (d == null) { // ... }

我也試過這個; 工作正常。

if (collection.find(queryFilter).iterator().tryNext() == null) { // ... }


我認為您的代碼或數據庫/集合可能存在其他問題。 使用新數據進行一些調試和測試可能會揭示真正的問題。

  • 您是否從mongo shellCompass工具檢查文檔是否已存在於集合中?
  • 您是否使用了正確的數據庫和集合名稱?
  • 每次測試運行后,您是否驗證數據庫中的數據是否已更新/插入?



collection.find(eq("name", doc.get("name"))).first() 從不返回 null。

使用我上面發布的代碼,當users集合為空時,查找查詢確實返回null

  1. collection.find()返回一個文檔數組。 你真正想要的是collection.findOneAndUpdate()

  2. findOneAndUpdate獲得TDoucment對象后,您可以使用 ObjectMapper 例如jackson將其映射回 java 對象

暫無
暫無

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

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