如何在Java 8流过滤器中基于子文档过滤Mongo文档

Bha*_*a S 1 java stream mongodb java-8 java-stream

我试图过滤子文档.

样本记录:

[Document{{_id=597608aba213742554f537a6, upp_id=, content_id=597608aba213742554f537a3, idmapping=Document{{ptype=PDF, clientid=12345, normalizedclientid=12345, systeminstanceid=, sourceschemaname=, platforminternalid=0987654321}}, batchid=null, locale=en_US}}]
Run Code Online (Sandbox Code Playgroud)

我需要使用idmapping.ptype = PDF进行过滤

MongoCursor<Document> cursor = mailboxitemCollection.find(whereClause).iterator();
List<Document> documentList = new ArrayList<Document>();

while (cursor.hasNext()) {
  Document object = cursor.next();
  documentList.add(object);
}

 List<Document> outList = documentList.stream()
        .filter(p -> p.getInteger(CommonConstants.VISIBILITY) == 1
            && (!StringUtils.isEmpty(req.ptype())? (p.getString("idmapping.ptype").equalsIgnoreCase(req.ptype())) : true)
            ).parallel().sequential().collect(Collectors.toCollection(ArrayList::new));

System.out.println(outList);
System.out.println(outList.size());
Run Code Online (Sandbox Code Playgroud)

我得到Null Point异常,无法从List documentList中读取sub/embed文档.

先感谢您!Bharathi

mgy*_*osi 5

使用mongo-java-driver,您无法直接访问子文档的字段.您应该获得子文档,然后在子文档的字段之后,如下所示:

String platformType =
 ((Document)p.get("idmapping")).getString("ptype");
Run Code Online (Sandbox Code Playgroud)

在您的情况下,将过滤器更改为以下内容:

.filter(p -> p.getInteger(CommonConstants.VISIBILITY) == 1  && (!StringUtils.isEmpty(req.ptype()) ? (((Document)p.get("idmapping")).getString("ptype").equalsIgnoreCase(req.ptype())) : true))
Run Code Online (Sandbox Code Playgroud)