I am trying to delete Older records present in my collection .
I have a collection named "user_track" , which consists of data in this format shown below
db.user_track.find().pretty()
{
"_id" : ObjectId("50c9afe5765fb0e4fea076ce"),
"cust_id" : "ddddd",
"symbol" : "WWWW",
"access_time" : "Thu Dec 13 2012 05:37:25 GMT-0500 (EST)"
}
{
"_id" : ObjectId("50c9afe7765fb0e4ffa076ce"),
"cust_id" : "eeeeeeeeee",
"symbol" : "WFC",
"access_time" : "Thu Dec 13 2012 05:37:27 GMT-0500 (EST)"
}
{
"_id" : ObjectId("522de3ae2191b0e41a7534dd"),
"cust_id" : "dsdsds",
"symbol" : "APPLE",
"access_time" : "Mon Sep 09 2013 11:05:18 GMT-0400 (EDT)"
}
In my collection , user_track , i want to keep only the current month's data (that is from Sep 01 2013 to current day ) and want to delete the rest of the records which doesn't belong to current month
I have tried to issue the below command , but i am not sure of how to issue this command to suit my requirement as the date i have is in different format .
db.user_track.delete( { 'access_time': {$lte: XXX} })
Please suggest .
In MongoDB, you are allowed to delete the existing documents from the collection using db. collection. deleteMany() method. This method deletes multiple documents from the collection according to the filter.
By default, remove() removes all documents that match the query expression. Specify the justOne option to limit the operation to removing a single document. To delete a single document sorted by a specified order, use the findAndModify() method.
You can give any Date with Javascript date
db.user_track.remove( { access_time : {"$lt" : new Date(year, month_0_indexed, day)} })
So for removing documents before 1 September 2013 your command should be
db.user_track.remove( { access_time : {"$lt" : new Date(2013, 8, 1) } })
September is the 9th month but the month field is zero indexed. So we make that as 8.
Mongo has a TTL feature on collections, I think this is a nice solution to such cases:
https://docs.mongodb.com/manual/tutorial/expire-data/
Basically something like:
db.log_events.createIndex( { "createdAt": 1 }, { expireAfterSeconds: 3600 } )
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