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

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

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 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