Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I remove older records from a collection in MongoDB?

Tags:

mongodb

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 }
like image 784
Swadeep Mohanty Avatar asked Dec 03 '22 12:12

Swadeep Mohanty


2 Answers

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

like image 194
helpdoc Avatar answered Dec 27 '22 02:12

helpdoc


db.collection.remove has been deprecated. You should use:
db.collection.deleteMany( { orderExpDate : {"$lt" : new Date(2017, 9, 1) } }))

like image 31
Brady R Avatar answered Dec 27 '22 02:12

Brady R