java - 如何在 Java 8 Stream Filter 中基于子文档过滤 Mongo 文档

标签 java mongodb java-8 stream 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}}]

我需要使用 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());

出现 Null Point 异常,无法从 List documentList 读取子/嵌入文档。

提前致谢! 巴拉蒂

最佳答案

使用 mongo-java-driver 不能直接访问子文档的字段。你应该得到子文档,然后是子文档的字段,如下所示:

String platformType =
 ((Document)p.get("idmapping")).getString("ptype");

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

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

关于java - 如何在 Java 8 Stream Filter 中基于子文档过滤 Mongo 文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45417846/

相关文章:

java - mongodb查询问题

java - 使用内部列表条件过滤列表

Java 8 流 .min() 和 .max() : why does this compile?

java - Android 3.1及以上版本自动开启定位服务

java 程序停止且没有错误

java - HTTP 状态 500 - 内部服务器错误 eclipse

java - iTextPDF : Set page size of PDF according to the size of the image to be inserted

mongodb - 我应该为多用户项目协作应用程序选择什么 NoSQL DB?

mongodb - 给定一条特定记录,检索 MongoDB 集合中的前一条记录

java - 使用 Java 8 搜索字谜