Querying by dates in MongoDB - the human way

Querying by dates - the human way

If you tried querying by dates in MongoDB, you know how much of a pain it can be. Even if you know the operators, typing the query will raise doubts. Is it ISODate, isoDate or IsoDate? What exactly is the date format? What was the date 2 weeks ago?

Date query

How does Mingo handle dates?

Mingo uses human-readable shorthands for dates in queries. Compare the following two queries:

Regular MongoDB date format:

  "createAt": {
    "$gte": ISODate("2020-02-21T00:00:00Z"), // or new Date(…)
    "$lt": ISODate("2020-02-28T00:00:00Z") // or new Date(…)

Using Mingo’s date shorthand:

  "createdAt": #lastWeek

There are two main types of date shorthands available:

Durations - periods between two moments

For example: #yesterday, #thisWeek, #lastWeek, #next7days

Duration date shorthands convert the keyword by using “less than” or “greater than” operators, or both. Duration shorthands use the # prefix.

Mingo provides the following specific keywords: #tomorrow, #today, #yesterday, #thisWeek, #lastWeek, #thisMonth, #lastMonth, #thisYear, #lastYear.

#yesterday translates to (example uses moment.js):

  "createdAt": {
    $gte: moment().subtract(1, 'day').startOf('day'),
    $lte: moment().subtract(1, 'day').endOf('day')

For more variable cases, you may use shorthands such as: #last30days, #last1month, #last2years, #next7days, #next12months, #2020-02-25, #since2020-02-25, #before2020-02-25.

Moments - single exact moments

For example: @2020-01-29, @2020-01-29T17:29

To query by a specific moment, use specific dates with the @ prefix, such as @2021-01-29 or @2020-01-29T17:29.

Mingo will understand any valid ISO 8601 format:

#2021-02-25 and @2021-02-25 are not the same. First refers to a duration (during that day) while the second points to the beginning of that day (a specific moment).

Download Mingo now

Mingo is free for personal use.

More articles

Hidden features

7 hidden features that make Mingo so addictive

Read more
Aggregation builder

Aggregation: simplified and visualized

Read more
Compare & Sync

Compare and sync entire MongoDB databases

Read more

Creating indexes with a breeze

Read more
Deep links

Deep linking from other apps or websites

Read more
Schema Analyzer

Analyze data structure

Read more
Human-readable dates

Querying by dates - the human way

Read more