使用java在MongoDB中查找单个内部字段

时间:2016-06-06 21:23:01

标签: java mongodb

在下面的文档中,我如何获得java中的filename字段?

> db.Audit.findOne({"auditorComments.filepath":"NewAudit6269242818132644222/withoutJS.txt"},{'auditorComments.$':1})
{
        "_id" : ObjectId("573a02dbe4b017e93448707b"),
        "auditorComments" : [
                {
                        "username" : "c9-security-1_ww@oracle.com",
                        "date" : ISODate("2016-05-20T23:59:29.889Z"),
                        "filename" : "withoutJS.txt",
                        "filepath" : "NewAudit6269242818132644222/withoutJS.txt",
                        "comment" : "test",
                        "bugnumber" : "1234"
                }
        ]
}

我有一个java代码,但它总是返回null

public String getFilename(String key) {
        DBCursor cur = audit.find(new BasicDBObject("auditorComments.filepath",key),new BasicDBObject ("auditorComments.$",1));
        String test = null;
        while (cur.hasNext()) {
            test = (String) cur.next().get("auitorComments.filename");
            System.out.print(test);
        }

        return null;
    }

1 个答案:

答案 0 :(得分:0)

试试这个:

public String getFilename(String key) {
    DBCursor cur = audit.find(new BasicDBObject().append("auditorComments.filepath", "NewAudit6269242818132644222/withoutJS.txt"));
    String test = null;
    while (cur.hasNext()) {
        BasicDBObject current_object = (BasicDBObject) cur.next();

        BasicDBList auditorComments = (BasicDBList) current_object.get("auditorComments");
        test = ((BasicDBObject) auditorComments.get(0)).getString("filename");
        System.out.println(test);
    }
    return test;
}