2015-04-07 285 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