如何使用Java从MongoDB的嵌入式密钥中获取价值?

时间:2016-02-16 11:38:59

标签: mongodb

我想使用java从Mongodb文档中提取嵌入式键( detokenObject.0.client.COUNTRY )的值。 我试过下面的代码。

 DBCursor cursor1 = coll1.find();
        while (cursor1.hasNext()) {
            BasicDBObject dbObject = (BasicDBObject)cursor1.next();
            BasicDBObject dbObject1= ((BasicDBObject)dbObject.get("detokenObject"));
            BasicDBObject dbObject2= ((BasicDBObject)dbObject1.get("0"));
            System.out.println("value is:::"+((BasicDBObject)dbObject2.get("client")).get("COUNTRY"));

        }

但是在运行之后,得到 ClassCastException(com.mongodb.BasicDBList不能转换为com.mongodb.BasicDBObject)

任何解决方案?

2 个答案:

答案 0 :(得分:0)

错误ClassCastException(com.mongodb.BasicDBList cannot be cast to com.mongodb.BasicDBObject)说明了一切,您正试图在BasicDBList字段上投放BasicDBObjectdetokenObject,这是一个列表。

使用

BasicDBList dbList = (BasicDBList) dbObject.get("detokenObject");

而不是

BasicDBObject dbObject1 = ((BasicDBObject)dbObject.get("detokenObject"));

然后通过client

的索引获取其元素dbList.getIndex(0);

即。您的最终代码应如下所示:

DBCursor cursor1 = coll1.find();
while (cursor1.hasNext()) {
    BasicDBObject dbObject = (BasicDBObject) cursor1.next();
    BasicDBObject dbList = (BasicDBList) dbObject.get("detokenObject");
    BasicDBObject dbObject1= (BasicDBObject) dbList.getIndex(0);
    System.out.println("value is::: " + (BasicDBObject) dbObject1.get("client")
                                                                 .get("COUNTRY"));
}

答案 1 :(得分:0)

我尝试过以下解决方案来锁定密钥,它对我有用。

public static Object getField(DBObject obj, String fieldName) {

       String[] fieldSections =fieldName.split("\\.");
       int i = 1;
       Object value = obj.getfieldSections[0]);
       while(i < fieldSections.length && value instanceof DBObject) {
           value = ((DBObject)value).get(fieldSections[i]);
           i++;
       }
       return value;
   }