Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

$subtract in updateMany() query of mongodb is not working?

This one is not working = 0 result found

user.updateMany(
    {
        status: { $in: ["registered", "applied"] },
        createdAt: { $lt: { $subtract: [new Date(), 1000 * 3600 * 24 * 7] } }
    }, 
    {
        $set: { status: "rejected"  }   
    }
)

This one is working

user.updateMany(
    {
        status: { $in: ["registered", "applied"] },
        createdAt: { $lt: new Date("08/11/2022") }
    }, 
    {
        $set: { status: "rejected"  }   
    }
)

What is issue? $subtract in find() is reason for not working ?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

$subtract is an aggregation operator. To use it in the filter/match criteria, you should use with $expr operator.

user.updateMany({
  $expr: {
    $and: [
      {
        $in: [
          "$status",
          [
            "registered",
            "applied"
          ]
        ]
      },
      {
        $lt: [
          "$createdAt",
          {
            $subtract: [
              new Date(),
              604800000  // 1000 * 3600 * 24 * 7
            ]
          }
        ]
      }
    ]
  }
},
{
  $set: {
    status: "rejected"
  }
})

Demo @ Mongo Playground

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading