当前位置: 首页 > 知识库问答 >
问题:

尝试使用MongoDB Java驱动程序更新文档

韦阳辉
2023-03-14
    < li >感谢您点击这个问题!我已经尽了最大努力让这件事尽可能彻底。 < li >但是,如果您需要进一步澄清,请随时告诉我! < li >如果您认为问题太长。你可以读第三个
  • 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文档告诉我它是一个TResault,它指向MongoIterable
  • https://mongodb.github.io/mongo-java-driver/3.11/javadoc/com/mongodb/client/MongoIterable.html#first()

共有2个答案

柳宏深
2023-03-14

>

  • collection.find()返回一个文档数组。这里实际需要的是collection.findOneAndUpdate()

    从findOneAndUpdate获取TDoucment对象后,可以使用ObjectMappere.g.jackson将其映射回java对象

  • 百里业
    2023-03-14

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

    从 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被传递给以下方法时,结果是:“###找到文档”。对于doc2,结果是“###找不到文档”。

    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) { // ... }
    

    < br >我认为您的代码或数据库/集合可能存在其他问题。使用新数据进行一些调试和测试可能会揭示真正的问题。

    • 您是否通过shell或Compass工具检查文档是否已经存在mongo集合中?
    • 您是否使用了正确的数据库和集合名称?
    • 每次测试运行后,您是否验证数据库中的数据是否已更新/插入?

    收集查找(eq(“名称”,doc.get(“名称)”)。first()从不返回null。

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

     类似资料:
    • 我的目标是使用聚合框架创建一个管道来对我的数据进行分组,然后将这个管道与java驱动程序一起使用。MongoDB v4.0.3 我使用MongoDB Compass创建了以下管道(减少到重要部分): 这导致以下(生成的)Java代码: 集合中$组阶段之前的数据如下所示: $组阶段应返回以下数据结构: 问题所在 Mongo Compass按预期预览了阶段的结果,但使用java驱动程序的阶段的结果非常

    • [debug]应用程序-update(){“_id”:{“$OID”:“5759542A4E0BF602ADCAB149”},“title”:“文本平铺”,“信誉”:0} [debug]application-org.mongodb.scala.observableImplicits$boxedobservable@61ddc581 [debug]application-onsubscribe:o

    • 问题内容: 参考文献: http://www.mongodb.org/display/DOCS/Java+Tutorial 对于mongo db来说还算是新手,但是我正在尝试更新集合中现有文档的一部分…不幸的是,上面的链接没有更新示例。 本质上,我只希望能够: 向文档添加新字段 将文档的现有字段更新为新值 这是我的代码(Grails + Groovy + Java + MongoDB + Java

    • 我正在尝试编写一个Java函数,将单词列表插入到集合中。我想为每个单词的唯一字段“单词”一个文档。我要插入的单词列表包含许多重复的单词,所以我希望我的函数只在集合中没有具有相同“word”值的文档时才插入文档。如果已经有一个具有相同“单词”值的文档,该函数不应该改变或替换这个文档,而是继续插入我的列表中的下一个单词。 我在字段“word”上创建了一个索引,以避免重复的文档并捕获重复的键Except

    • 问题内容: 您好,我想将chrome驱动程序更新到最新版本,但ant会找到有关更新驱动程序的任何信息,只是有关安装它的信息。我需要怎么做才能将驱动程序更新到最新版本? 问题答案: chromedriver是一个独立的可执行文件。只需将您的现有版本替换为较新的版本即可。 从https://sites.google.com/a/chromium.org/chromedriver/downloads下载