1

This question is mostly popular but with a slight twist; I need to delete few records by when it was created, using its _id. I do not have any date, createdAt fields as I see that mongo uses its _id for the createdAt timestamp.

How do I delete a recored, say created 30 days ago, using this gist?

const date = new Date();
const daysToDeletion = 30;
const deletionDate = new Date(date.setDate(date.getDate() - daysToDeletion));

const db = <your-database>

db.messages.remove({_id : {$lt : deletionDate}});

The above returns a CastError

What would work, and as Ive said, I do not have a createdAt field:

db.messages.remove({createdAt : {$lt : deletionDate}});
Sylar
  • 11,422
  • 25
  • 93
  • 166
  • Possible duplicate of [Can I query MongoDB ObjectId by date?](https://stackoverflow.com/questions/8749971/can-i-query-mongodb-objectid-by-date) – Alex Blex Dec 06 '17 at 10:42

3 Answers3

5

Use mongo shell:

db.collection.find({"_id": { "$gt": ObjectId.fromDate(new Date('2017-10-01'))}})

Use mongoose:

Model.find({ _id: { $gt: mongoose.Types.ObjectId.createFromTime(new Date('2018-01-01')) } })

will find the needed docs.

foodtooth
  • 146
  • 8
0

var id = new ObjectId( Math.floor(deletionDate .getTime() / 1000).toString(16) + "0000000000000000")

db.messages.remove({createdAt : {$lt : id}});

Shubham
  • 1,396
  • 9
  • 17
0

You need to extract the timestamp from the object _id. So you could do something like:-

db.messages.find({}).forEach(function(rec) {
    var recDate = rec._id.getTimestamp();
    // Then here cast your deletionDate and recDate to preferred string format, e.g:-
    var recDateString = recDate.getMonth()+1+'-'+recDate.getDate()+'-'+recDate.getFullYear();
    var deletionDateString = deletionDate.getMonth()+1+'-'+deletionDate.getDate()+'-'+deletionDate.getFullYear();

    if (deletionDateString == recDateString ){
        db.messages.remove({_id:rec._id});
    }
}
Mr Davros
  • 100
  • 10