Juan  Henriquez
Juan Henriquez

Reputation: 131

What is the best way to query for a date saved in MongoDB with the format YYYY-MM-DD?

My current documents looks like this:

{
  _id: 123,
  nextBillingDate: '2018-02-12',
}

I need a way to query for documents that have a nextBillingDate less or equal to today.

For example, if I have the following documents:

[
  {
    _id: 123,
    nextBillingDate: '2018-02-12'
  },
  {
      _id: 789,
      nextBillingDate: '2018-02-01'
  },
  {
      _id: 654,
      nextBillingDate: '2018-02-28'
  }
]

And today is 2018-02-12, the result of the query needs to contain the documents with the _id 123 and 789.

Upvotes: 1

Views: 396

Answers (1)

Saravana
Saravana

Reputation: 12817

Try this query

db.col.find(
    {$expr : 
        {$lte : 
            [
                {$dateFromString : {dateString : "$nextBillingDate"}},
                new Date("2018-02-12")
            ]
        }
    }
)

using aggregation

db.col.aggregate([
    {$match :
        {$expr : 
            {$lte : 
                [
                    {$dateFromString : {dateString : "$nextBillingDate"}},
                    new Date("2018-02-12")
                ]
            }
        }
    }
])

Upvotes: 1

Related Questions