Skip to content

Instantly share code, notes, and snippets.

@Stoffo
Created October 29, 2015 12:29
Show Gist options
  • Save Stoffo/fd4a0a70be89e8d7ce15 to your computer and use it in GitHub Desktop.
Save Stoffo/fd4a0a70be89e8d7ce15 to your computer and use it in GitHub Desktop.
Remove Documents older than x days in MongoDB
var date = new Date();
var daysToDeletion = 120;
var deletionDate = new Date(date.setDate(date.getDate() - daysToDeletion));
printjson(deletionDate);
var db = db.getSiblingDB('db')
db.getMongo().setSlaveOk();
printjson(db.messages.find({insertDate : {$lt : deletionDate}}).count());
//delete old Messages:
db.messages.remove({insertDate : {$lt : deletionDate}});
@OlivierJM
Copy link

3 years after, this just helped, it took time to understand why $lt was used instead of $gt.
Thanks for this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment