首页 文章

使用java在mongo 3中查找嵌套值

提问于
浏览
0

我的mongo集合中有一个文档,如下所示:

{ 
  "timestamp": 1460442540,
  "page": "home",
  "misc": {
             "color": "red",
             "light": "off" 
          }
}

我希望能够做的是在页面上满足某个条件时返回misc.color的值 .

这就是我所拥有的:

//find my query match
   Document value = mongoDBService.getCollection(collectionName)
            .find(eq("page", "home")).first();

    //prints json described above
    LOG.info(value.toString());

    //prints "misc" subdocument
    LOG.info(value.get("misc").toString());

    //null pointer
    LOG.info(value.get("misc.color").toString());

有没有办法在这里处理我错过的点符号?理想情况下,我希望此查询是动态的,因此它可以处理点表示法值和更高级别的值 .

我正在使用mongodb-driver 3.4.2 .

2 回答

  • 0

    您可以将代码更新到下面 .

    Document value = mongoDBService.getCollection(collectionName)
                .find(eq("page", "home")).first();
    
    LOG.info(value.get("misc", Document.class).getString("color"));
    
  • 3

    你可以试试这个:

    BasicDBObject query = (BasicDBObject)(value.get("misc")).getString("color");
    

相关问题