简体   繁体   中英

how to get a value of sub collection in array in mongodb using java

How to print the value of filename??

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

the java code i used is:

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

But im unable to get the field value... plzz help me to fix this.

thanx in advance

files is an array of embedded documents. So, you can get BasicDBList first, then iterate on it's fields and find value corresponding to 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);
        }
     }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM