2015-04-07 284 views
0

我想提取在“location”字段中提到的所有这些地方,并且不希望下面的json中的其他字段,但无法提取,因为它是嵌套的。可以任何人都帮助我?从mongodb中提取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

你到目前为止尝试了什么? – BetaRide

+0

@BetaRide我已更新我的问题,并添加了我的一个试用版 –

回答

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

输出只找位置,你应该使用蒙戈aggregation,下面的查询将获取所有lcoations array

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