·8 min read

Stop Writing ISODate() by Hand: How MongoDB Date Macros Save Hours Every Week

You've been there. You need to query MongoDB for documents from the last week, so you open a new tab, search "JavaScript date 7 days ago," copy a Stack Overflow snippet, wrap it in ISODate(), and paste it into your query. Five minutes later, you're doing it again for "start of this month." There's a better way.

The ISODate() Problem Every MongoDB Developer Knows

MongoDB's date handling forces you to construct ISODate() objects manually for time-based queries. Want to find orders from today? You write:

db.orders.find({
  createdAt: {
    $gte: ISODate("2026-04-19T00:00:00.000Z"),
    $lt:  ISODate("2026-04-19T23:59:59.999Z")
  }
})

Need last week's data? More date math:

db.analytics.find({
  timestamp: {
    $gte: ISODate("2026-04-12T00:00:00.000Z"),
    $lt:  ISODate("2026-04-19T00:00:00.000Z")
  }
})

This gets old fast. You're spending more time calculating dates than analyzing data.

What Are MongoDB Date Macros?

Date macros replace manual ISODate() construction with readable shortcuts. Instead of calculating timestamps, you type #today or #last7days.

The same queries become:

db.orders.find({ createdAt: #today })
db.analytics.find({ timestamp: #last7days })

Clean. Fast. No date math.

Essential Date Macros for Daily Development

Here are the date macros you'll use most often.

Current time periods

  • #today — current day (00:00:00 to 23:59:59)
  • #yesterday — previous day
  • #thisWeek — current week (Monday to Sunday)
  • #thisMonth — current month
  • #thisYear — current year

Relative periods

  • #last7days — past 7 days including today
  • #last30days — past 30 days including today
  • #lastWeek — previous complete week
  • #lastMonth — previous complete month

Time boundaries

  • #startOfDay — today at 00:00:00
  • #endOfDay — today at 23:59:59
  • #startOfWeek — Monday at 00:00:00
  • #startOfMonth — first day of month at 00:00:00

Using Date Macros in Find Queries

Date macros work in any MongoDB query where you'd use ISODate().

Single date filters

Find today's user signups:

db.users.find({ registeredAt: #today })

Find orders from last month:

db.orders.find({ orderDate: #lastMonth })

Range queries

Find documents between two relative dates:

db.logs.find({
  timestamp: {
    $gte: #startOfWeek,
    $lt:  #endOfDay
  }
})

Complex conditions

Combine date macros with other filters:

db.products.find({
  category:  "electronics",
  createdAt: #last30days,
  status:    "active"
})

Date Macros in Aggregation Pipelines

Date macros work across all 14 aggregation pipeline stages, not just $match.

Match stage

db.sales.aggregate([
  { $match: { saleDate: #thisMonth } },
  { $group: { _id: "$product", total: { $sum: "$amount" } } }
])

Group by date ranges

db.events.aggregate([
  {
    $bucket: {
      groupBy:    "$eventDate",
      boundaries: [#startOfMonth, #today, #endOfMonth],
      default:    "other"
    }
  }
])

Conditional logic

db.users.aggregate([
  {
    $addFields: {
      isRecentUser: {
        $cond: {
          if:   { $gte: ["$registeredAt", #last30days] },
          then: true,
          else: false
        }
      }
    }
  }
])

For a deeper walkthrough of pipelines, see our MongoDB aggregation pipeline guide.

Advanced Date Macro Patterns

Combining multiple macros

Find documents created this week but not today:

db.tasks.find({
  createdAt: {
    $gte: #startOfWeek,
    $lt:  #startOfDay
  }
})

Nested document queries

Query dates in embedded documents:

db.orders.find({
  "shipping.deliveredAt": #yesterday,
  "payment.processedAt": #thisWeek
})

Array element matching

Find documents with array elements matching date criteria:

db.projects.find({
  "milestones.dueDate": #thisMonth
})

Time Zone Considerations

Date macros use your system's local time zone by default. This matters when your application and database run in different time zones.

For UTC-based queries, many MongoDB clients let you specify time zone handling in connection settings. Check your client's documentation for timezone configuration options.

When working across time zones, be explicit about your date boundaries and test edge cases around midnight transitions.

Performance Benefits

Date macros improve performance in two ways:

  • Query planning — MongoDB's query planner can optimize queries with consistent date patterns better than ad-hoc ISODate() constructions.
  • Index usage — queries with predictable date ranges (like #today or #thisMonth) make better use of compound indexes on date fields.
  • Developer speed — you write queries faster without stopping to calculate dates or look up syntax.

For applications with heavy date-based filtering, the time savings add up quickly.

MongoDB Clients with Date Macro Support

Not all MongoDB clients support date macros. Most require manual ISODate() construction for every time-based query.

Mongon includes 35+ date macros that work across queries and all 14 aggregation pipeline stages. The macros expand to proper ISODate() objects automatically, so your queries run normally while you write them faster.

The native macOS client eliminates the copy-paste-calculate cycle that slows down database work.

FAQ

What happens if I use a date macro in a query sent to MongoDB directly?

Date macros are a client-side feature. They're converted to ISODate() objects before the query is sent to MongoDB, so the database sees normal ISO date strings.

Do date macros work with MongoDB Atlas?

Yes. Date macros are processed by your MongoDB client, not the database server. They work with any MongoDB deployment including Atlas, self-hosted instances, and local development databases.

Can I create custom date macros?

This depends on your MongoDB client. Some clients allow custom macro definitions; others provide a fixed set. Check your client's documentation for customization options.

Do date macros affect query performance?

Date macros typically improve performance by encouraging consistent query patterns that MongoDB's optimizer handles efficiently. The conversion from macro to ISODate() happens client-side with minimal overhead.

How do date macros handle leap years and month boundaries?

Date macros use standard Date primitives for calculations, so they handle leap years, varying month lengths, and daylight saving time transitions correctly.

Are date macros case sensitive?

Most implementations are case-sensitive. #today works, but #Today or #TODAY typically don't. Check your client's syntax requirements.

Can I use date macros in stored JavaScript functions?

No. Date macros are a client-side feature that gets converted before reaching MongoDB. Server-side JavaScript functions need to use standard ISODate() or JavaScript Date constructors.

Conclusion

Stop calculating dates by hand. Date macros turn time-consuming date math into readable shortcuts.

Your queries become cleaner. Your development gets faster. Your date logic becomes consistent across your application.

The next time you need to query MongoDB by date, reach for #today instead of opening that JavaScript date calculator tab.

Related Articles

Try date macros for free35+ macros included · macOS 15.1+