MongoDb在java中访问嵌套文档

时间:2013-07-22 07:12:11

标签: java mongodb

我是MongoDB的新手。我试图访问mongodb中的嵌套文档。我的示例文档是

{
    "Advertisement" : {
        "html" : "zxcxz"
    },
    "Notification" : {
        "date_from" : ISODate("2013-06-30T18:30:00Z"),
        "date_too" : ISODate("2013-07-16T18:30:00Z"),
        "description" : "vcvc",
        "url" : "vcvc"
    },
    "_id" : ObjectId("51e4f10ee4b08e0a6ebcbe46"),
    "group_name" : "sumit",
    "target_audience" : {
        "gender" : "male",
        "section" : "xyz",
        "catagory" : "--Computer--",
        "location" : {
            "country" : "--Country--",
            "state" : "--State--",
            "city" : "--City--"
        }
    }
}

我正试图从target_audience获取性别。我的java代码是

DBCursor f=con.coll.find(query);
while(f.hasNext())
{
    f.next();
    gender=(String) f.curr().get("target_audience.gender");
}

但它返回null。

1 个答案:

答案 0 :(得分:3)

DBCursor.next()DBCursor.curr()的结果是BasicDBObject。对于包含嵌入文档的密钥,BasicDBObject.get(key)会返回BasicDBObject

DBCursor f=con.coll.find(query);
while(f.hasNext())
{
    BasicDBObject result = (BasicDBObject) f.next();
    BasicDBObject target = (BasicDBObject) result.get("target_audience");
    gender = (String) target.get("gender");
}