Im creating a query to delete data more than seven days ago. But its not deleting data from previus month.
Example: I have data created at 02/03/2022 and 01/03/2022 and this data will be deleted, but the data with date 25/02/2002(month 02) will not.
Here is my code:
let selectedDay = moment().subtract(7, "d").toDate();
let remove = await mongoose.connection.db.collection("mycollection")
.deleteMany({
createdAt: {
$lt: selectedDay
}
});
I see you have your custom date format. In that case you can use _id property which is of type ObjectId. It has createdAt built in. You can try this query:
If you are going to use specific knowledge about an ObjectID internal structure please use the official API.
Also take a look at TTL indexes. You might have what you want right out of the box what you need. But I think your indexed fields need to be real date data type. Another reason to migrate.
I see… The problem is the type. But every time I format the type change to string. How can I insert date with format(“DD-MM-yyyy HH:mm.ss”) with format date?
You should not care about how the date is formatted in your stored data, it is probably some kind of number that takes less space than a string. The way it is displayed is ISO compliant. It simply needs to be the correct date type. If an ISO compliant format is not okay for you, you may display it in the format of your choice later at the presentation of your application.