Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

117
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda