How can I remove older documents from a collection, older than seven days?
{ "orderID" : "456986", "orderType" : "OnlinePurchase", "orderStatus" : "expired", "address" : "Hexel", "payement" : "Card", "isDomestic" : true, "orderExpDate" : ISODate("2017-09-20T20:36:11.000Z"), "shipped" : false }
For removing documents before Date, your command should be:
db.collection.deleteMany( { orderExpDate : {"$lt" : new Date(YEAR, MONTH, DATE) } })
For removing records before 1 October 2017, the command will be:
db.collection.deleteMany( { orderExpDate : {"$lt" : new Date(2017, 9, 1) } })
October is the 10th month. If the month field is zero indexed, then we use 9, otherwise use 10.
...........................
This will remove all records older than seven days:
db.collection.deleteMany( { orderExpDate : {"$lt" : new Date(Date.now() - 7*24*60*60 * 1000) } })
Update: collection.remove is deprecated
db.collection.remove
has been deprecated. You should use:db.collection.deleteMany( { orderExpDate : {"$lt" : new Date(2017, 9, 1) } }))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With