0

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.

4

1 回答 1

0

好的,找到了解决方案。就我而言,我知道字段名称,因此我可以检索 DBObject,然后检查每个字段名称并相应地对其进行类型转换以检索它。*想知道 Javascript 的仙境是多么自由。幸运的是,在 Java 中,我们几乎总是知道我们会得到什么。:)

解决方案如下所示:

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

如果检索到 BSOONList,则相应地对其进行类型转换。BSONList 可能包含 BSONList 或 BSONObject,因此如果您不知道要检索什么,它会变得混乱。在这些情况下,动态类型转换很有帮助。

于 2012-12-26T05:43:07.260 回答