Mongo Template天的差值,与db字段比较



我在db中有文档,像下面这样,我希望减去当前日期,得到天数的差异,并将差异与存储在db中的值作为同一文档的有效性进行比较。

所以我的查询应该获取startDate和当前日期之差大于有效性的所有文档

//mongo document snap
{
"campaignDuration": {         
"startDate": {
"$date": "2021-10-21T11:39:59.657Z"
},
},
"attributes":{
"validity":2
}
}

有人可以帮助我在春天使用mongo模板查询

试试这个:

db.collection.aggregate([
{
$match: {
$expr: {
$gte: [
{
$dateDiff: {
startDate: "$$NOW",
endDate: "$startDate",
unit: "day"
}
},
"$attributes.validity"
]
}
}
}
])

$dateDiff是MongoDB 5.0版本中新引入的。如果运行旧版本,则用{$multiply: [{$subtract: ["$startDate", "$$NOW"]}, 1000*60*60*24]}

替换表达式

我根据Wernfried Domscheit的答案编写了spring mongo模板(https://stackoverflow.com/a/69632053/7009165)

AggregationOperation matchOperation = (context) -> {
Document matchDocument = new Document("$expr", new Document("$gte",
Arrays.asList(
new Document("$dateDiff", new Document()
.append("startDate", "$$NOW")
.append("endDate", "$startDate")
.append("unit", "day")),
"$attributes.validity"
)));
return new Document("$match", matchDocument);
};
mongoTemplate.aggregate(Aggregation.newAggregation(matchOperation), "collection", OutputClass.class);