Home > Net >  MongoError: Invalid $project :: caused by :: Unknown expression $dateSubtract
MongoError: Invalid $project :: caused by :: Unknown expression $dateSubtract

Time:09-28

{
    $project: {
        logoutTime: {
            $dateSubtract: {
                startDate: new Date(),
                unit: "hour",
                amount: 3,
            },
        },
    },
},

Error: Invalid $project :: caused by :: Unknown expression $dateSubtract

Using Nodejs as Platform ``"mongoose": "^5.9.18",```

Also Tried With

{
    $addFields: {
        logoutTime: {
            $dateSubtract: {
                startDate: new Date(),
                unit: "hour",
                amount: 3,
            },
        },
    },
},

Getting Similar type of Error

MongoError: Invalid $addFields :: caused by :: Unrecognized expression '$dateSubtract'

CodePudding user response:

The $dateSubtract operator is only available starting Mongo version 5, you can check this playground and see that the syntax you're using is working fine.

Luckily you can just use the normal mathematic operators as they also support date substitution, you just have to provide the number to subtract in milliseconds, like so:

db.collection.aggregate([
  {
    $project: {
      logoutTime: {
        $toDate: {
          $subtract: [
            "$$NOW",
            10800000
          ]
        }
      }
    }
  }
])

Mongo Playground

  • Related