0

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"}}
                            ]}

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"}}

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

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

enter image description here

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.: 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.

0

1 Answer 1

2

There are couple of things incorrect here.

field - Change from Data to Books

separator - Change from semicolon to comma

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));
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for your help!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.