0

I wrote a MongoDB query to fetch orders that were closed on a given date (matching year and month):

const orders = await OrderModel.find({
  $expr: {
    $and: [
      { $eq: ['$entityId', entityId] },
      { $ne: ['$closingDate', null] },
      { $eq: [{ $year: '$closingDate' }, date.getFullYear()] },
      { $eq: [{ $month: '$closingDate' }, date.getMonth() + 1] },
    ],
  },
}).lean();

Turns out my local MongoDB version (3.6) is higher than the one on the dev environment (3.4.14), and therefore $expr isn't supported. Is there an alternative for older version I can use?

Note: I read the other thread regarding this topic, but I couldn't extract an answer from that as it covers a different use case.

FlushBG
  • 183
  • 1
  • 10
  • Have you tried avoiding `$expr`? Like [this example](https://mongoplayground.net/p/WVN0lZWRhlL) – J.F. Nov 12 '21 at 09:28
  • @J.F. Yes, avoiding it is what I'm trying to do! I just don't know for this specific use case - using the $month and $year operators. Does a standard .find() query support them? – FlushBG Nov 12 '21 at 09:31
  • Hmm that's true, you are using `$year` and `$month`. So maybe you can use `aggregate` with `$match` instead of `find`. – J.F. Nov 12 '21 at 09:39
  • I changed the query to look for `closingDate: { $ne: null, $gte: current, $lt: next }` and it appears to be working. Thanks! – FlushBG Nov 12 '21 at 09:52
  • Please don't paste screenshots, use formatted text. See https://meta.stackoverflow.com/q/285551/3027266 – Wernfried Domscheit Nov 12 '21 at 16:13
  • There is no need for `$expr` - but I refuse to give answer by transcribing from a screenshot. – Wernfried Domscheit Nov 12 '21 at 16:16
  • @WernfriedDomscheit Sorry, I wasn't aware. I fixed it. Also, the issue was resolved by using `$gte` and `$lt` operators. Still, I'd love to see a more closer alternative - like using `aggregate`, for example. Cheers! – FlushBG Nov 13 '21 at 17:23

1 Answers1

0

Whenever you have to work with dates/times then I recommend the moment.js library. Looks like, you want to query the data from the current month. Then you could write it like this:

db.OrderModel.find({
  entityId: entityId,
  closingDate: {
    $gte: moment().startOf('month').toDate(), 
    $lte: moment().endOf('month').toDate() 
  }
})

You don't need closingDate: {$ne: null}, it's redundant.

Wernfried Domscheit
  • 54,457
  • 9
  • 76
  • 110