Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove old records in mongodb based on Month

Tags:

mongodb

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 .

like image 776
Pawan Avatar asked Sep 10 '13 10:09

Pawan


People also ask

How do I delete multiple collections in MongoDB?

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.

What is the command used to delete records in MongoDB?

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.


2 Answers

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.

like image 193
bsd Avatar answered Oct 26 '22 13:10

bsd


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 } )

like image 36
JAR.JAR.beans Avatar answered Oct 26 '22 13:10

JAR.JAR.beans