I have document in db like below manner, I wish to subtract the current date, get difference in days and compare the difference with value stored in db as validity in same document.
So my query should fetch all the documents whose startDate
and current date difference is greater than validity
//mongo document snap
{
"campaignDuration": {
"startDate": {
"$date": "2021-10-21T11:39:59.657Z"
},
},
"attributes":{
"validity":2
}
}
Can someone help me with the query in spring using mongo template
Wernfried Domscheit :
Try this one:\ndb.collection.aggregate([\n {\n $match: {\n $expr: {\n $gte: [\n {\n $dateDiff: {\n startDate: "$$NOW",\n endDate: "$startDate",\n unit: "day"\n }\n },\n "$attributes.validity"\n ]\n }\n }\n }\n])\n\n$dateDiff was newly introduced in MongoDB version 5.0. If you run an older version then replace the expression by {$multiply: [{$subtract: ["$startDate", "$$NOW"]}, 1000*60*60*24]}",
2021-10-19T13:47:30