I am working on a route that stores last n days of user history using Nodejs and Mongodb.
Say I want to keep track of count
. This is what I was planning to have my schema as:
count: [
type: Number
default: 0
]
Each element in the array will correspond to a day and the value would be the count of some action, the user performed. What I want to do is keep only 30 days of data, i.e. 30 elements in the array. Each day the element corresponding to the day before the 30th day should be deleted.
The obvious method is to pop an element each day and insert a new element each day at 12 AM. But that feels too bruteforcy. Do you guys have any better approach to this?
2
Answers
$pop
and$push
in the same updateIn this case I assume your 30 day is 3 day and I want to push 10 into count array.
mongoplayground
This sounds like a business logic, which needs to be done in a scheduler.
With a scheduler, you can do this: