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

148
Visualizações
Am I using Mongo's $and and $expr incorrectly?

Here is my query:

   ctas.updateMany({
      $and: [
          {$expr: { $lt: ['$schedule.start', () => Date.now()] }},
          {$expr: { $gt: ['$schedule.end', () => Date.now()] }}
      ]
    },
   {
    $set: {isActive: true}
  }).then(res => {
    const { matchedCount, modifiedCount } = res;
    console.log(`Successfully matched ${matchedCount} and modified ${modifiedCount} items.`)
    
  }).catch(e => console.error(e));

I'm absolutely positive that start is less than Date.now() and end is greater than Date.now(), but I'm not getting any matches. Is my syntax wrong?

a snippet of my document in mongo:

schedule: {
    start: 1642564718042,
    end: 3285129434744
}

Edit: In case it makes a difference, I'm writing this code as a mongo scheduled trigger.

Update: If I replace the second expression with an obviously truth expression, { isActive: false }, it matches all the documents. Obviously Date.now()*2 (what I used to set schedule.end) is greater than Date.now(), so why is that second expression failing?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Missing $. And make sure your field paths are correct. $schedule.start and $schedule.end.

And another concern is that both schedule.start and schedule.end are with Timespan value. So you need to cast them to date via $toDate.

db.collection.update({
  $and: [
    {
      $expr: {
        $lt: [
          {
            $toDate: "$schedule.start"
          },
          new Date()
        ]
      }
    },
    {
      $expr: {
        $gt: [
          {
            $toDate: "$schedule.end"
          },
          new Date()
        ]
      }
    }
  ]
},
{
  $set: {
    isActive: true
  }
})

Sample Mongo Playground

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