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
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 } )
I have found a solution to address this issue .
var date=new Date();
date.setDate(date.getDate() - 1);
db.user_track.remove({"access_time":{"$lt":date}});
I will make this run automatically by putting these lines in a bash file and scheduling that script using a cron tab .
Please share your views if this is a valid solution or not ??
In addition to other answers you may be interesting in the "Time to live” collection feature: http://docs.mongodb.org/manual/tutorial/expire-data/
It's useful to automatically expire/remove documents from a collection after specific period of time.
Probably there is a cleaner solution but this should work:
Create new Data field from date strings:
var cursor = db.user_track.find()
while (cursor.hasNext()) {
var doc = cursor.next();
db.user_track.update(
{_id : doc._id},
{$set : {access_time_ : new Date(doc.access_time)}})
}
Now you can retrieve some records by comparing dates:
db.user_track.find({access_time_: {$lt: new Date("Sep 01 2013 00:00:00 GMT+00:00")}})
If everything works as expected remove obsolete records:
db.user_track.remove({access_time_: {$lt: new Date("Sep 01 2013 00:00:00 GMT+00:00")}})
In the future use date objects not strings