【问题标题】:Trying to update a document using MongoDB Java Driver尝试使用 MongoDB Java 驱动程序更新文档
【发布时间】:2019-12-04 02:10:17
【问题描述】:

谢谢

  • 我只想感谢您点击此问题!我已尽最大努力使这一切尽可能彻底。
  • 但是,如果您需要进一步澄清任何事情,请随时告诉我!
  • 如果您认为问题太长。您可以阅读第三和第四部分并在此处发布您自己的解决方案!

设置

  • 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 Documentation 告诉我这是一个TResult,它指向MongoIterable<TResult>。我被困在这里了。
  3. 代码结果是最终没有插入/更新任何文档。

参考

【问题讨论】:

    标签: java mongodb mongo-java-driver mongo-collection


    【解决方案1】:

    我尝试了一些代码,但效果很好。这与您的代码没有太大区别。

    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() 永远不会返回 空。

    使用我上面发布的代码,当 users 集合为空时,查找查询确实返回了 null

    【讨论】:

    • 我认为你是对的......看起来我在我的主课中使用了错误的方法哈哈。谢谢你的帮助!
    【解决方案2】:
    1. collection.find() 返回一个文档数组。你真正想要的是collection.findOneAndUpdate()

    2. findOneAndUpdate 获得TDoucment 对象后,可以使用ObjectMapper 例如jackson 将其映射回java 对象

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-02
      • 1970-01-01
      • 2017-08-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多