Remove old data from MongoDB

db.statistic.insertMany([
{
event: 'pageview',
userId: 'user1',
createdAt: new Date('July 1, 2022 14:10:00'),
},
...
// more documents here
...
{
event: 'pageview',
userId: 'user10',
createdAt: new Date('July 10, 2022 11:22:00'),
},
]);
db.statistic.remove({ 
createdAt: {
$lt: new Date(today - X days)
}
});
cron "0 0 0 * * *" do
db.statistic.remove({
createdAt: {
$lt: new Date(today - X days)
}
});
end
npm install cron
const { CronJob } = require('cron');

const job = new CronJob(
'0 0 0 * * *',
(() => {
db.statistic.remove({
createdAt: {
$lt: new Date(today - X days),
},
});
}),
null,
true,
'America/Los_Angeles',
);
db.statistic.createIndex({
createdAt: 1,
}, {
expireAfterSeconds: 60 * 60 * 24 * 7,
});

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store