Search code examples
javamongodbcursor

Filter mongodb cursor in a subfield of document


I trying to perform a query in my mongo database using java code. I want to filter the result of the query using cursor. Basically I want to filter the cursor results two times. My query return some documents, and I want to filter them based on a field of document and a sub-field of the first field. For example:

 DBCursor cursor = coll.find(query);
 while(cursor.hasNext()) {
       BasicDBObject obj = (BasicDBObject) cursor.next();
        System.out.println(obj.getString("images")); 
}

Return the image field from all quered documents. What should I do if I want to return the field "link" which is a subfield of field "images"? I tried obj.getString("images").getString("link"), however it doesn't work. Images is an array with three fields the first one is the filed "link". When the above return is the following: [ { "link" : "http://distilleryimage1.ak.instagram.com/fc7c5_7.jpg" , "phash" : "01000010101000101010111101" , "persons" : 1}] . I want to return just the first field link.


Solution

  • Just get images as ArrayList:

    ArrayList<BasicDBObject> images = (ArrayList<BasicDBObject>)obj.get("images"); 
    for(BasicDBObject image: images)
    {
         String link = image.getString("link");
         .......
    }