skip to Main Content

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


  1. $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

    Login or Signup to reply.
  2. 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}}});
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search