使用 Java 驱动程序 3.4 将数据附加到 MongoDB 文档中的数组 [英] appending data to array in MongoDB-Document using Java Driver 3.4

查看:44
本文介绍了使用 Java 驱动程序 3.4 将数据附加到 MongoDB 文档中的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 MongoDB Java Driver 3.4 并且想要更新 Mongo-DB 集合中的文档(ID 为12").目前,文档如下所示:

I am using MongoDB Java Driver 3.4 and want to update a document (with id "12") in a Mongo-DB collection. Currently, the document looks as follows:

{"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"来更新此文档:

I want to update this document by adding the following object to array "Data":

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

为此我写了以下java代码:

To this end I wrote the following java code:

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...) 有问题:

The IDE indicates there is something wrong with the last statement (collection.update...) by showing me this:

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

I don't know what this error message is supposed to tell me. There is a semicolon at the end of the statement. Does anybody know what's wrong with the java code?

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

P.S.: This is not a duplicate to (MongoDB Java) $push into array My question relates to Java Driver 3.4. The other question relates to an earlier version with totally different classes.

推荐答案

这里有几处不正确.

字段 - 从 Data 更改为 Books

field - Change from Data to Books

separator - 从 semicolon 更改为 comma

separator - Change from semicolon to comma

method - 从 update 更改为 updateOne,您可以直接传递 Document.

method - Change from update to updateOne and you can pass Document directly.

 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));

这篇关于使用 Java 驱动程序 3.4 将数据附加到 MongoDB 文档中的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆