Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

113
Views
Store only given days' of data on mongodb

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?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

$pop and $push in the same update

In this case I assume your 30 day is 3 day and I want to push 10 into count array.

db.collection.update({},
[
  {
    $set: {
      count: {
        $cond: {
          if: { $gte: [ { $size: "$count" }, 3 ] },
          then: {
            $concatArrays: [
              { $slice: [ "$count", 0, { $subtract: [ { $size: "$count" }, 1 ] } ] },
              [ 10 ]
            ]
          },
          else: { $concatArrays: [ "$count", [ 10 ] ] }
        }
      }
    }
  }
],
{
  multi: true
})

mongoplayground

about 4 years ago · Juan Pablo Isaza Report

0

This sounds like a business logic, which needs to be done in a scheduler.

With a scheduler, you can do this:

db.collection.updateMany(query, {$pull: {count: { type: 30DaysAgoDate}}});
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!