繁体   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