我的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值。我应该如何找到给定设备的选定值?
答案 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