MongoDB检索条目java

时间:2018-01-29 15:44:55

标签: java mongodb

我有一个MongoDB,看起来像这样:

{
"_id" : ObjectId("57b16601494957499ae07619"),
"URL" : "some url",
"Text" : "some text ",
"Timestamp" : ISODate("2016-08-15T01:07:00.000Z"),
"RelatedActiveTopics" : [ 
    "apple"
],
"Language" : "en",
"PlatformType" : "NewsAggregator",
"Platform" : "Bing",
"SentimentScore" : 0.0,
"Source" : "Times Publishing Group",
"RelatedDomains" : [ 
    {
        "DomainName" : "Energie",
        "Confidence" : 1
    }

到目前为止,我的代码看起来像这样:

while (cursor.hasNext()) {
            BasicDBObject dom = (BasicDBObject) cursor.next();
            BasicDBList relatedD = (BasicDBList) dom.get("RelatedDomains");

            List<String> res = new ArrayList<String>();

            DBObject dbObject = (DBObject) dom.get("RelatedDomains");

这给了我输出DomainName和Confidence,但我只需要DomainName,我怎么才能得到DomainName?

2 个答案:

答案 0 :(得分:0)

只需致电dbObject.get("DomainName")

答案 1 :(得分:0)

您可以尝试使用java 8流来输出DomainName值列表。

List<String> res = relatedD.stream().
       map(item -> (String)((DBObject)item).get("DomainName")).
       collect(Collectors.toList());

使用for循环

for(Object item : relatedD) {
  res.add((String)((DBObject)item).get("DomainName"));
}