Home:ALL Converter>Mongo Template Difference between days and compare with db field

Mongo Template Difference between days and compare with db field

Ask Time:2021-10-19T21:27:15         Author:sgarg5

Json Formatter

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

Author:sgarg5,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/69631728/mongo-template-difference-between-days-and-compare-with-db-field
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
yy