如何使用java在mongodb中获取数组中的子集合值

时间:2015-03-30 15:07:09

标签: java mongodb

如何打印文件名的值??

>db.register.find().pretty()
{
     "name":"abc",
     "files":[
                {
                       "filename":"web.html",
                       "content_type":"text/html"
                },
                {
                       "filename":"import.doc",
                       "content_type":"text/doc"
                }
            ]
}

我使用的java代码是:

            String a = request.getParameter("Name");
            MongoClient mongo = new MongoClient("localhost", 27017);
            DB db = mongo.getDB("smart");
            DBCollection coll = db.getCollection("register");
            DBCursor doc = coll.find(new BasicDBObject("name", a));

     while(doc.hasNext())
                {
            BasicDBObject dbObject = (BasicDBObject)doc.next();    
            String fname = dbObject.getString("files.filename");
                    out.println(fname);
                }

但我无法获得现场价值...... plzz帮助我解决这个问题。

提前

thanx

1 个答案:

答案 0 :(得分:0)

files是一组嵌入式文档。因此,您可以先获取BasicDBList,然后对其字段进行迭代,找到与filename对应的值: -

    while (doc.hasNext()) {
        BasicDBObject dbObject = (BasicDBObject) doc.next();
        BasicDBList list = (BasicDBList) dbObject.get("files");
        for(Object obj : list ){
            String fname = ((BasicDBObject)obj).getString("filename");
            System.out.println(fname);
        }
     }