Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

151
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!