在Jasper Studio中使用MongoDB查询时,创建动态或可选过滤器(参数)可以通过以下步骤实现:
以下是一个示例,展示如何在Jasper Studio的MongoDB查询中创建动态过滤器:
首先,在Jasper Report的参数面板中定义需要的参数。例如:
<parameter name="productName" class="java.lang.String"/>
<parameter name="minPrice" class="java.lang.Double"/>
<parameter name="maxPrice" class="java.lang.Double"/>
在MongoDB查询中使用这些参数来构建动态条件。可以使用$and
和$or
逻辑运算符来组合多个条件。
<queryString><![CDATA[{
"collectionName": "yourCollection",
"query": {
"$and": [
{"$expr": {"$eq": [{"$ifNull": ["$productName", ""]}, {"$ifNull": ["$P{productName}", ""]}]}},
{"$expr": {"$gte": ["$price", {"$ifNull": ["$P{minPrice}", -Infinity]}]}}},
{"$expr": {"$lte": ["$price", {"$ifNull": ["$P{maxPrice}", Infinity]}]}}]
}
}]]></queryString>
使用$ifNull
操作符来处理参数为空的情况,确保查询不会因为缺少参数而失败。
以下是一个完整的Jasper Report XML片段,展示了如何实现上述逻辑:
<?xml version="1.0" encoding="UTF-8"?>
<jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name="DynamicFiltersReport" pageWidth="595" pageHeight="842" columnWidth="555" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20">
<parameter name="productName" class="java.lang.String"/>
<parameter name="minPrice" class="java.lang.Double"/>
<parameter name="maxPrice" class="java.lang.Double"/>
<queryString><![CDATA[{
"collectionName": "yourCollection",
"query": {
"$and": [
{"$expr": {"$eq": [{"$ifNull": ["$productName", ""]}, {"$ifNull": ["$P{productName}", ""]}]}},
{"$expr": {"$gte": ["$price", {"$ifNull": ["$P{minPrice}", -Infinity]}]}}},
{"$expr": {"$lte": ["$price", {"$ifNull": ["$P{maxPrice}", Infinity]}]}}]
}
}]]></queryString>
<!-- 其他报表定义 -->
</jasperReport>
$and
和$or
的使用,确保逻辑正确。通过上述方法,可以在Jasper Studio中有效地创建和使用动态过滤器,提升报表的灵活性和实用性。
领取专属 10元无门槛券
手把手带您无忧上云