0

On a monthly basis, I want to delete all documents older than 1 month from one of my collections. An example document from the collection looks something like this:

{
    _id: ObjectId("56e75f1ce851695805ead8ae"),
    createDate: ISODate("2016-03-15T01:02:20.821Z"),
    foo: "bar"
}

I want to have this task be automatically scheduled to happen so it requires no human input--say, as a cron job--and so I would like for it to have as little logic as possible.

How would I query for documents where the createDate is older than 1 month? I had thought to try something like this:

db.col.find({createDate: {$lt: ISODate(ISODate().getTime() - 1000*3600*24*30)}});

... where I create a new ISODate with the current time minus 1 month of milliseconds, but this isn't returning any data. It's also kinda ugly, even if it did work. How would I go about accomplishing this?

nasukkin
  • 2,460
  • 1
  • 12
  • 19
  • here you can find some working solutions https://stackoverflow.com/questions/19819870/date-query-with-isodate-in-mongodb-doesnt-seem-to-work – alfredopacino Dec 06 '17 at 00:42
  • I don't really see an answer to my question in there. I know how to query according to a static ISODate already, but that's not my question. – nasukkin Dec 06 '17 at 00:48

2 Answers2

1

You can create TTS index to delete data more than 30 days. It will delete data automatically after 30 days.

db.col.createIndex( { "createDate": 1 }, { expireAfterSeconds: 2592000 } )

Sohan.Choudhury
  • 201
  • 2
  • 4
0

Well, I figured it out. It seems my syntax was a bit wrong... not entirely certain how this correct syntax works, to be honest, but it does what I need.

db.col.find({createDate: {$lt: new Date((new Date())-1000*3600*24*30)}});
nasukkin
  • 2,460
  • 1
  • 12
  • 19
  • It shouldn't be much of a real issue but if you have MongoDB deployed in different instances across the globe you might want to make sure that the server are all in the same timezone. I think `new Date()` uses system time instead of UTC – Tan Kim Loong Dec 06 '17 at 02:11