Remove old records in mongodb based on Month

后端 未结 5 1149
[愿得一人]
[愿得一人] 2020-12-30 04:13

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

相关标签:
5条回答
  • 2020-12-30 04:30

    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.

    0 讨论(0)
  • 2020-12-30 04:33

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

    0 讨论(0)
  • 2020-12-30 04:37

    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 ??

    0 讨论(0)
  • 2020-12-30 04:38

    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.

    0 讨论(0)
  • 2020-12-30 04:43

    Probably there is a cleaner solution but this should work:

    1. 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)}})
      }
      
    2. 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")}})
      
    3. 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")}})
      
    4. In the future use date objects not strings

    0 讨论(0)
提交回复
热议问题