我想提取" location"中提到的所有这些地方。字段,并不希望下面的json中的其他字段。但由于它是嵌套的,因此无法提取。任何人都可以帮助我吗?
DBCursor cursorTotal = coll.find(obje);
while (cursorTotal.hasNext()) {
DBObject curNext = cursorTotal.next();
System.out.println("data::"+curNext.get("list.myList.location");
}
我的" curNext"输出为::
{
"_id": {
"$oid": "51ebe983e4b0d529b4df2a0e"
},
"date": {
"$date": "2013-07-21T13:31:11.000Z"
},
"lTitle": "Three held for running CISF job racket",
"list": {
"myList": [
{
"location": "Germany"
},
{
"location": "Geneva"
},
{
"location": "Paris"
}
]
},
"hash": -1535814113,
"category": "news"
}
我希望输出为
Germany,Geneva,Paris
答案 0 :(得分:1)
我在这里等了很长时间才得到答案,最后我得到了我正在寻找的东西......只是注意到我的答案,所以其他人可以从中受益
DBCursor cursorTotal = coll.find(obje);
while (cursorTotal.hasNext()) {
DBObject curNext = cursorTotal.next();
String res=curNext.toString();
JsonElement jelement = new JsonParser().parse(res);
JsonObject jobject = jelement.getAsJsonObject();
jobject = jobject.getAsJsonObject("list");
JsonArray jarray = jobject.getAsJsonArray("myList");
jobject = jarray.get(0).getAsJsonObject();
String result = jobject.get("location").getAsString();
System.out.println("all places::"+result);
}
答案 1 :(得分:0)
如果只查找你应该使用mongo aggregation的位置,下面的查询将获取所有的lcoations数组
db.collectionName.aggregate({
"$unwind": "$ner.nerList"
},
{
"$group": {
"_id": "$_id",
"location": {
"$push": "$ner.nerList.location"
}
}
},
{
"$project": {
"location": "$location",
"_id": 0
}
})
不幸的是我不知道如何在Java中转换它,但是,我在下面找到了有助于您以java格式转换上述查询的链接 Mongo Java aggregation driver