Java 如何在Spring data mongodb中基于条件投影字段?

Java 如何在Spring data mongodb中基于条件投影字段?,java,mongodb,spring-data-mongodb,Java,Mongodb,Spring Data Mongodb,我正在尝试根据搜索条件获取匹配的文档。除了有一个名为priceHistory的列表字段外,一切正常,它有两个属性:1)价格和2)价格日期。我只需要投影priceHisotry字段,并且仅当今天的价格可用时,否则它必须显示为空。priceHistory字段不是搜索条件的一部分,而是结果(预测) 尝试使用简单的条件,但最终基于 价格历史日期字段 尝试使用$Cond,但无法转换 转换成Java等价物 最后一种方法是迭代 结果设置并实现所需的输出 "priceHistory": [

我正在尝试根据搜索条件获取匹配的文档。除了有一个名为priceHistory的列表字段外,一切正常,它有两个属性:1)价格和2)价格日期。我只需要投影priceHisotry字段,并且仅当今天的价格可用时,否则它必须显示为空。priceHistory字段不是搜索条件的一部分,而是结果(预测)

  • 尝试使用简单的条件,但最终基于 价格历史日期字段
  • 尝试使用$Cond,但无法转换 转换成Java等价物
  • 最后一种方法是迭代
    结果设置并实现所需的输出

    "priceHistory": [
                    {
                        "price": "20019.75",
                        "dateForPrice": "Tue Sep 09 02:00:00 IST 2019"
                    },
    {
                        "price": "20234.75",
                        "dateForPrice": "Tue Sep 08 02:00:00 IST 2019"
                    }
    {
                        "price": "20234.75",
                        "dateForPrice": "Tue Sep 08 02:00:00 IST 2019"
                    }
                ]
    
    条件运算符.when(标准.where(“priceHistory.price”).gte(今天)) 。然后(dynamicQuery.fields().include(value))。否则(“”)

是否有一种方法可以将此条件添加到查询对象中,以便DB可以处理它,而不是迭代每个文档并处理响应。

您可以在MongoDB查询中筛选字段“priceHistory”,如下所示:

db.collection.aggregate([
    {
    $project: {
        priceHistory: {
            $filter: {
                input: "$priceHistory",
                as: "ph",
                cond: {
                    $and: [
                        { $gte: ["$$ph.dateForPrice", start] },   // start time of the day 00:00:00 
                        { $lte: ["$$ph.dateForPrice", end ]  }    // end time of the day 23:59:59
                    ]
                }
            }
        }
    }        
}
])

从当前日期动态传递开始和结束日期和时间。这将过滤掉价格历史记录。

您可以在MongoDB查询中过滤字段“priceHistory”,如下所示:

db.collection.aggregate([
    {
    $project: {
        priceHistory: {
            $filter: {
                input: "$priceHistory",
                as: "ph",
                cond: {
                    $and: [
                        { $gte: ["$$ph.dateForPrice", start] },   // start time of the day 00:00:00 
                        { $lte: ["$$ph.dateForPrice", end ]  }    // end time of the day 23:59:59
                    ]
                }
            }
        }
    }        
}
])

从当前日期动态传递开始和结束日期和时间。这将过滤掉价格历史记录