Andrew Taylor
Andrew Taylor

Reputation: 628

Mongo Aggregation ignoring date range filter in $match

I have an Mongo aggregation query that is returning correct results except for the date range supplied in the $match. It basically returns the same results with or without the date range values. Basically, I'm trying to determine the total number of delivered messages per location for a specific date.

const startOfToday = moment()
  .startOf('day')
  .tz('America/New_York')

const endOfToday = moment()
  .endOf('day')
  .tz('America/New_York')

// Show Todays Entries Only
let fromDate = new Date(startOfToday);
let toDate = new Date(endOfToday);

  Model.aggregate([
  {
    $match: {
      'analytics.twilio.status': 'delivered',
      'analytics.twilio.date': { $gte: fromDate },
      'analytics.twilio.date': { $lte: toDate }
    }
  },
  {
    $lookup: {
      from: 'branches',
      localField: 'branch',
      foreignField: '_id',
      as: 'branch'
    }
  },
  {
    $match: {
      'branch.0.org_id': orgId
    }
  },
  { $unwind: '$branch' },
  {
    $group: {
      _id: '$branch.name',
      delivered: { $sum: 1 }
    }
  }
])
  .sort('_id')
  .then(response => {
    if (response) {
      res.json(response);
    }
  });
 });

Here is a truncated version of the schema:

const Wip =  new Schema({
      branch: {
        type: Schema.Types.ObjectId,
        ref: 'branches'
      },
      analytics: {
        twilio: {
          sid: { type: String },
          status: { type: String },
          error: { type: String },
          date: { type: Date }
        }
      },
        date: { type: Date, default: Date.now }
      });

    const BranchSchema = new Schema({
        name: { type: String, required: true },
        org_id: { type: String, required: true },
        clinic_id: { type: String, required: true },
    })

I thought the issue may be the $lookup, but the issue still occurs if I remove the $lookup and use the $branch field as the $group id.

What am I overlooking ? Do I need to add some sort of $cond ?

Upvotes: 1

Views: 713

Answers (1)

Ashh
Ashh

Reputation: 46441

Your need to wrap both $gte and $lte inside the single curly braces

Model.aggregate([
  {
    $match: {
      'analytics.twilio.status': 'delivered',
      'analytics.twilio.date': { '$gte': fromDate, '$lte': toDate }
    }
  }
])

Upvotes: 2

Related Questions