Dates

Querying by dates in MongoDB - the human way

Querying by dates in - the human way

Anyone who tried to query by dates in MongoDB knows what 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?

Aggregation

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 @2020-01-29 or @2020-01-29T17:29.

Mingo will understand any valid ISO 8601 format: https://en.wikipedia.org/wiki/ISO_8601

#2020-02-25 and @2020-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).

Try Mingo

intuitive • fast • reliable

More articles

Hidden features

7 hidden features that make Mingo so addictive

Read more
Aggregation

Aggregation: simplified and visualized

Read more
Compare & Sync

Compare and sync entire MongoDB databases

Read more
Indexes

Creating indexes with a breeze

Read more
Deep links

Deep linking from other apps or websites

Read more
Analyzing

Analyzing data consistency

Read more
Dates

Querying by dates in - the human way

Read more