Mongo和Java读取嵌套文档值

时间:2014-01-29 12:39:06

标签: java json mongodb

我的mongo馆藏包含以下文件

{

"syslog": [
    {
        "alertId": "N/A",
        "time": "06:46:57",
        "device": "10.10.20.1"
    },
    {
        "alertId": "N/A",
        "time": "06:47:30",
        "device": "10.10.20.2"
    }
]
}

现在我想只读取给定设备的值。

假设我设置了device =“10.10.20.2”,它只会显示"alertId": "N/A", "time": "06:47:30", "device": "10.10.20.2"这个我编写java代码如下

BasicDBObject criteria = new BasicDBObject();                                       

criteria.put("syslog.device","10.10.20.2");
DBCursor cur = coll.find(criteria);
while(cur.hasNext() && !isStopped()) {
    String json = cur.next().toString(); 
}//end of while

当我打印json时,它显示了整个json值。我应该如何找到给定设备的选定值?

1 个答案:

答案 0 :(得分:3)

您应该使用$elemMatch运算符来投影数组字段。您应该按如下方式更新您的查询:

db.collection.find({"syslog.device" : "10.10.20.2"},{syslog : {$elemMatch : {device : "10.10.20.2"}}})

在Java中:

BasicDBObject criteria = new BasicDBObject();                                       
criteria.put("syslog.device","10.10.20.2");

BasicDBObject elemMatchObj = new BasicDBObject();
elemMatchObj.put("$elemMatch", new BasicDBObject("device", "10.10.20.2"));

DBCursor cur = coll.find(criteria, new BasicDBObject("syslog", elemMatchObj));
while(cur.hasNext() && !isStopped()) {
    String json = cur.next().toString(); 
}//end of while