Home > Mobile >  Mongo DB $getField doesn't work as expected
Mongo DB $getField doesn't work as expected

Time:09-23

I want to filter classes that are still on going using $match with moment js. But, the $getField doesn't work as expected.

$match: {
    $expr: {
      $lt: [ 
          moment(new Date()).valueOf(),
          parseInt(moment({ $getField: "classStartDate" }, 'x').add({ $getField: "numberOfWeeks"}, 'weeks').valueOf())
      ]
   }
}

CodePudding user response:

Why so complicated? Simply try this:

$match: {
    $expr: {
       $lt: [ 
         "$$NOW",
         {$add: ["$classStartDate", {$multiply: ["$numberOfWeeks", 1000*60*60*24*7 ]} ] }
       ]
   }
}

As you are obviously using Mongo version 5.0, you can also use

$match: {
    $expr: {
       $lt: [ 
         "$$NOW",
         { $dateAdd: { startDate: "$classStartDate", unit: "week", amount: "$numberOfWeeks" } }
       ]
   }
}

If $$NOW does not work use moment().toDate()

  • Related