【问题标题】:How to filter Mongo document based on sub-document in Java 8 Stream Filter如何在 Java 8 Stream Filter 中基于子文档过滤 Mongo 文档
【发布时间】:2018-01-07 03:23:42
【问题描述】:

我正在尝试过滤子文档。

样本记录:

[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());

遇到空点异常,无法从 List documentList 中读取子/嵌入文档。

提前感谢您! 婆罗洲

【问题讨论】:

  • NullPointer 在哪里
  • 可能reqp.get*null.parallel().sequential()...是多余的,你也可以用collect(Colllectors.toList())代替。
  • @Eugene - Nullpointer in '(!StringUtils.isEmpty(req.ptype())? (p.getString("idmapping.ptype").equalsIgnoreCase(req.ptype())) : true )'
  • 我说的是它是多余的。您尝试将顺序流更改为并行流,然后再次更改回顺序流。这是毫无意义的。
  • 您可以使用Objects.requireNonNull检查每个值是否为null,例如:Objects.requireNonNull(p.getString("idmapping.ptype"), "idmapping").equalsIgnoreCase(...)

标签: java mongodb java-8 stream java-stream


【解决方案1】:

使用 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))

【讨论】:

    猜你喜欢
    • 2021-06-29
    • 1970-01-01
    • 2015-07-18
    • 2020-04-14
    • 2020-04-19
    • 2010-10-04
    • 2018-01-07
    • 1970-01-01
    • 2022-07-06
    相关资源
    最近更新 更多