Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete documents by date comparison between sum of date and numeric fields and current timestamp

The documents in the MongoDB collection have the following schema (showing only relevant fields):

{
    "TTLinSeconds" : 1800,
    "lastUpdatedTimestamp" : ISODate("...")
}

I need to delete all documents where current timestamp is greater than lastUpdatedTimestamp plus the value stored in the TTLinSeconds field. Thanks in advance for your suggestions.

like image 364
Jacek Avatar asked Oct 23 '25 15:10

Jacek


2 Answers

This might work (to delete field between 2017-01-25T00:30:00Z and 2017-01-26T23:59:00Z ):

  db.collectionName.remove({
       $and : [
        {"lastUpdatedTimestamp": { 
           $gte:   ISODate("2017-01-25T00:30:00Z"), 
           $lt :   ISODate("2017-01-26T23:59:00Z")
       },
       {"TTLinSeconds" : value}
      ]
    }  

Suggestion:

I would recommend you to use the common naming convention for your variables.

Reference :

https://docs.mongodb.com/manual/reference/operator/update/currentDate/

like image 93
Sourabh Bhagat Avatar answered Oct 25 '25 11:10

Sourabh Bhagat


You could do this using $where as:

db.collectionName.remove({$where:"new Date().getTime() > this.lastUpdatedTimestamp.getTime() + (this.TTLinSeconds * 1000)"})
like image 23
oblivion Avatar answered Oct 25 '25 11:10

oblivion