【问题标题】:appending data to array in MongoDB-Document using Java Driver 3.4使用 Java Driver 3.4 将数据附加到 MongoDB-Document 中的数组
【发布时间】:2017-07-01 22:22:16
【问题描述】:

我正在使用 MongoDB Java 驱动程序 3.4 并且想要更新 Mongo-DB 集合中的文档(id 为“12”)。目前,该文档如下所示:

{"id" : "12", "Data" : [{"Author" : "J.K. Rowling", 
                              "Books" : {"Harry Potter 1" : "$15.99", "Harry Potter 2" : "$16.49", "Harry Potter 3" : "$19.49"}},
                             {"Author" : "Philip Roth", 
                              "Books" : {"American Pastoral" : "$12.99", "The Human Stain" : "$39.49", "Indignation" : "$29.49"}}
                            ]}

我想通过将以下对象添加到数组“Data”来更新此文档:

{"Author" : "Stephen King", "Books" : {"Rose Red" : "$12.69", "Faithful" : "$9.49", "Throttle" : "$8.49"}}

为此我写了如下java代码:

Document doc = new Document().append("Author", "Stephen King")
                             .append("Data", new Document("Rose Red", "$12.69")
                                            .append("Faithful" : "$9.49")
                                            .append("Throttle" : "$8.49"));                                                                                     

collection.update({"id", "12"}, {$push: {"Data" : doc.toJson()}});

IDE 通过向我显示以下内容表明最后一条语句 (collection.update...) 有问题:

我不知道这个错误信息应该告诉我什么。语句末尾有一个分号。有人知道java代码有什么问题吗?

P.S.:这不是重复 (MongoDB Java) $push into array 我的问题与 Java Driver 3.4 有关。另一个问题与具有完全不同类的早期版本有关。

【问题讨论】:

    标签: java mongodb updates mongo-java-driver


    【解决方案1】:

    这里有几处不正确。

    字段 - 从 Data 更改为 Books

    分隔符 - 从 semicolon 更改为 comma

    方法 - 将update更改为updateOne,您可以直接传递Document

     Document doc = new Document("Author", "Stephen King")
                .append("Books", new Document("Rose Red", "$12.69").append("Faithful", "$9.49").append("Throttle", "$8.49"));
    
    collection.updateOne(new Document("id", "12"), Updates.push("Data", doc));
    

    【讨论】:

    • 感谢您的帮助!
    猜你喜欢
    • 2017-12-07
    • 1970-01-01
    • 2021-06-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-08
    • 1970-01-01
    相关资源
    最近更新 更多