0

I am trying to use $gte in aggregation based on property from aggregation in Nodejs.

const twelveHours = 12 * 60 * 60 * 1000;
const pipeline = [
  { $addFields: { 
    twelveHoursBeforeStart: { $subtract: ['$startDate', twelveHours] } } // this works
  },
  { match: { 
    endDate: { $gte: new Date('$twelveHoursBeforeStart') }, // <- HERE pass a variable    
  },
]

I have tried different solutions like:

{ match: { 
  endDate: { $gte: '$twelveHoursBeforeStart' },
},

but non of them actually works

1 Answer 1

1

You can do both the operations in $match stage,

  • $expr expression match with aggregation $gte operator, first argument is endDate and second subtract condition
const twelveHours = 12 * 60 * 60 * 1000;
const pipeline = [
  {
    $match: {
      $expr: {
        $gte: [
           "$endDate",
           { $subtract: ["$startDate", twelveHours] }
        ]
      }
    }
  }  
]

Playground

Sign up to request clarification or add additional context in comments.

4 Comments

This isn't working on Node because it is compiled to: { $expr: { $gte: ['$endDate', { $subtract: ['$startDate', twelveHours] }] } }, Same result will have if compare to undefined. It expects a date object
is it string type or date type in your collection?
Isn't it same if we just do { match: { endDate: { $gte: { $subtract: ["$startDate", twelveHours] } } } },
no its not same, because $subtract is an aggregation expression operator and we are accessing internal startDate field as well so we can't use internal field in match condition, so that is why it requires to use $expr and there are 2 different syntax for simple $gte and expression $gte

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.