Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

119
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda