Remove old records in mongodb based on Month

后端 未结 5 1172
[愿得一人]
[愿得一人] 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: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

提交回复
热议问题