MongoDB extracting values from BasicDBObject (Java)

前端 未结 2 1965
醉梦人生
醉梦人生 2020-12-03 08:42

I am having trouble retrieving values from queried documents in MongoDB.

For example, the doc structure is like:

    {
        \"_id\": {
                    


        
相关标签:
2条回答
  • 2020-12-03 09:39

    There's no way to chain a property name like you're doing using the Java driver (gets for sure, and according to the this, put isn't supposed to work either).

    You'll need to get the objects one at a time like you suggested.

    ((DBObject)obj.get("response")).get("resData")
    

    See here for a potential future feature that would allow your syntax to possibly work (although, likely with a new method name).

    0 讨论(0)
  • 2020-12-03 09:43

    I ran into the same problem and I wrote a small function to fetch chained properties.

    private Object getFieldFromCursor(DBObject o, String fieldName) {
    
        final String[] fieldParts = StringUtils.split(fieldName, '.');
    
        int i = 1;
        Object val = o.get(fieldParts[0]);
    
        while(i < fieldParts.length && val instanceof DBObject) {
            val = ((DBObject)val).get(fieldParts[i]);
            i++;
        }
    
        return val;
    }
    

    I hope it helps.

    0 讨论(0)
提交回复
热议问题