我正在尝试过滤子文档。
示例记录:
[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/