我正在尝试根据搜索条件获取匹配的文档。一切正常,除了有一个名为priceHistory的List字段外,它具有两个属性1)price和2)date作为价格。我只需要投影priceHisotry字段,并且只有在今天的价格可用的情况下,否则必须将其显示为null。 priceHistory字段不是搜索条件的一部分,而仅是结果(投影)。
最后的办法是遍历
重新设置并获得所需的输出
"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"
}
]
ConditionalOperators.when(Criteria.where(“ priceHistory.price”)。gte(todaysDate)) .then(dynamicQuery.fields()。include(value))。otherwise(“”);
有没有一种方法可以将此条件添加到Query对象,以便DB可以为它工作,而不是遍历每个文档并处理响应。
答案 0 :(得分:0)
您可以在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
]
}
}
}
}
}
])
从当前日期开始动态传递开始和结束日期和时间。这将过滤掉价格历史记录。