Search code examples
mongodbmongodb-querymongodb-update

MongoDB - $subtract is not working in updateMany()


This one is not working with 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 the issue? Is $subtract in find() the reason for not working?


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