title: retrieve array from mongodb using java with mongodb api
body: <p>I understand that there are many questions which as for the same and they are answered well. The problem is all those questions use MongoDBObject, MongoDBList to retrieve arrays. My problem is I am using <a href="http://api.mongodb.org/java/3.0/index.html?overview-summary.html" rel="noreferrer">http://api.mongodb.org/java/3.0/index.html?overview-summary.html</a> api and I am having hard time retrieving array and adding elements to it. I have to use MongoCollection, MongoDatabase and MongoClient. I am trying to solve an assignment from mongodb course. The problem statement is to find an array and update it in mongod.</p>
  
  <p>Here is what I have tried</p>
  
  <pre><code>      Document post = null; Bson filter = new Document("permalink",
        permalink); Bson projection = new Document("comments", true);
        List&lt;Document&gt; comments = postsCollection.find(filter)
        .projection(projection).into(new ArrayList&lt;Document&gt;());
        System.out.println(comments);
  
        post = postsCollection.find(Filters.eq("permalink",
        permalink)).first();
  
        Document newComment = new Document();
  
        newComment.append("author", name); newComment.append("body", body);
        if (email != null &amp;&amp; (!email.equals(""))) {
        newComment.append("email", email); }
  
        comments.add(newComment);
  
        Bson filter2 = new Document("_id", post.get("_id"));
        System.out.println(comments); post =
        postsCollection.find(filter).first();
  
        postsCollection.updateOne(filter2, new Document("$unset",new
        Document("comments",true))); postsCollection.updateOne(filter2, new
        Document("$set", new Document( "comments", comments)));
  </code></pre>
  
  <p>This does not create a new comment. Instead, it creates another <strong>comments</strong> array in <strong>comments</strong> array itself. THe array should be updated in <strong>student</strong></p>
  
  <p>Here is the json data</p>
  
  <pre><code>{
  "_id" : ObjectId("55d965eee60dd20c14e8573e"),
  "title" : "test title",
  "author" : "prasad",
  "body" : "test body",
  "permalink" : "test_title",
  "tags" : [ 
      "test", 
      "teat"
  ],
  "date" : ISODate("2015-08-23T06:19:26.826Z"),
  "comments" : [ 
      {
          "_id" : ObjectId("55d965eee60dd20c14e8573e"),
          "comments" : [ 
              {
                  "_id" : ObjectId("55d965eee60dd20c14e8573e"),
                  "comments" : []
              }, 
              {
                  "author" : "commented",
                  "body" : "something in comment",
                  "email" : "some@thing.com"
              }
          ]
      }, 
      {
          "author" : "commented",
          "body" : "something in comment",
          "email" : "some@thing.com"
      }
  ]
  </code></pre>
  
  <p>}</p>