简体   繁体   中英

Embedded Array Retrieval Mongodb Java

I've been trying to get this query, but I have been unable to roll my heads over this one.

The Object looks like this:

{
   restaurantName:'abc',
   reviews:[
              {
                 text:'Its awesome!'
                 person: 'John Doe'
              }
              {
                 text:'Nice Ambience'
                 person: 'Davis'
              }

           ]
}

The intent is to find out all the reviews text present in the document. How do I do this using JAVA driver for Mongo. I keep getting Class Cast Exceptions

Following is the code:

Set fields = new TreeSet();

BasicDBList e ;
    try {
        DBObject dbObject;
        while (cursor.hasNext()) {
        doc = new Document();
         e = (BasicDBList) cursor.next().get("reviews");
          for(BasicDBObject temp: e){
               fields.addAll(temp.keySet());
           }
        }
          //System.out.println(cursor.next());
        }

The error I am getting is:

Exception in thread "main" java.lang.ClassCastException: com.mongodb.BasicDBObject cannot be cast to java.util.ArrayList at org.poly.darshan.utils.DataExtractor.main(DataExtractor.java:57)

The code mentioned above intends to find the unique fields present in the sub-objects. But the problem is more or less the same.

Ok found the Solution. In my case I know the field names, so I can retrieve the DBObject and then check for each field name and typecast it accordingly to retrieve it. *Wonders how free the wonderland of Javascript is. Luckily in Java, we mostly always know what we are going to get.:)

The solution looks something like this:

while (cursor.hasNext()) {
        doc = new Document();
        e = cursor.next();
        for (String field : e.keySet()) {
            if (field.equals("reviews")) {
            BSONObject temp = (BSONObject) e.get(field);
            System.out.println(temp.toString());
            }
                 //else print the other String values
        }
}

If BSOONList is retrieved, then typecast it accordingly. BSONList may contain BSONList or BSONObject, so it gets messy if you dont know what you want to retrieve. Dynamic Typecasting is helpful in these cases.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM