Kolban
Kolban

Reputation: 15246

Aggregate puzzle with $match and date comparison

I am having a puzzle with comparison of dates. I have created a simplified story to help illustrate. Imagine the following collection of documents:

{ 
    "_id" : "A", 
    "t1" : ISODate("2018-01-23T00:00:00.000+0000")
}
{ 
    "_id" : "B", 
    "t1" : ISODate("2018-01-22T00:00:00.000+0000")
}
{ 
    "_id" : "C", 
    "t1" : ISODate("2018-01-21T00:00:00.000+0000")
}

This is three documents with dates in 2018.

Now imagine an aggregation with a $match entry that looks as follows:

{
  $match:
  {
    "t1": {
      $gte: {
        $dateFromString: {
          dateString: "2017-02-08T12:10:40"
        }
      }
    }
  }
}

What this should do is match all the documents as the date I am comparing against is back in 2017. However, what I am finding is that no documents match. This is the first phase in an aggregation pipeline but with no documents being passed forward, that's the end of the current story.

Can anyone see where I might be going wrong?

Upvotes: 2

Views: 1445

Answers (2)

paparoch
paparoch

Reputation: 450

check out this npm module: https://www.npmjs.com/package/mongodb-extended-json it'll automatically convert { '$date': "2016-01-01T00:00:00.000Z"} to a date object for you

Upvotes: 0

s7vr
s7vr

Reputation: 75914

You have to use $expr (3.6 mongo version ) to use the aggregation functions (dateFromString) in the $match stage. $match in its simple form only supports query operators.

Compare query operators vs aggregation comparison operators.

Change to

{"$match":{"$expr":{"$gte":["$t1",{"$dateFromString":{"dateString":"2017-02-08T12:10:40"}}]}}}

Upvotes: 3

Related Questions