MongoDB $millisecond Operator

Beginner
⏱️ 7 min read
📚 Updated: Jul 2026
🎯 4 Examples
Date Operations

What You’ll Learn

The $millisecond operator extracts the millisecond portion (0–999) from a BSON Date inside MongoDB aggregation pipelines. Use it for sub-second precision in logs, metrics, latency analysis, and high-frequency event data.

01

Extract ms

Date → 0–999.

02

Syntax

One date argument.

03

Sub-Second

Within the second.

04

Timezone Option

Local time support.

05

Use Cases

Logs, latency.

06

Related Ops

$second, $minute.

Definition and Usage

In MongoDB’s aggregation framework, the $millisecond operator takes a date expression and returns an integer between 0 and 999. For example, $millisecond applied to ISODate("2024-06-15T14:30:45.123Z") returns 123, and ISODate("2024-06-15T14:30:45.987Z") returns 987.

Milliseconds are the finest standard date component MongoDB exposes alongside $second, $minute, and $hour. They are useful when events occur many times per second and you need to distinguish or order them precisely.

💡
Beginner Tip

$millisecond only returns the ms part within the current second (0–999). It does not return the full Unix timestamp in milliseconds. For elapsed time between dates, use $subtract instead.

📝 Syntax

The $millisecond operator takes a date expression, or an object with date and timezone:

mongosh
{ $millisecond: <dateExpression> }

// With timezone:
{
  $millisecond: {
    date: <dateExpression>,
    timezone: <tz>
  }
}

Syntax Rules

  • Argument — any expression that evaluates to a BSON Date (field, $$NOW, or literal).
  • Return value — integer from 0 to 999 (milliseconds within the second).
  • Null input — returns null when the date is null or missing.
  • Timezone — optional; use Olson timezone IDs like "America/New_York".
  • Use inside $project, $addFields, $set, $match (with $expr), or $group.

💡 $millisecond vs $second vs $minute

14:30:45.123Z$hour: 14, $minute: 30, $second: 45, $millisecond: 123
$millisecond — 0–999 (fraction of the second)
$subtract — use for full elapsed milliseconds between two dates

⚡ Quick Reference

QuestionAnswer
Operator typeAggregation expression operator (date extraction)
ArgumentsOne date expression
Return typeInteger (0–999)
Timezone supportYes (object form with timezone)
MongoDB version3.4+
From field
{
  $millisecond: "$recordedAt"
}

ms component

.123 seconds
{
  $millisecond:
    ISODate(
      "2024-06-15T14:30:45.123Z"
    )
}

Returns 123

In $project
{
  ms: {
    $millisecond:
      "$eventAt"
  }
}

Add computed field

With timezone
{
  $millisecond: {
    date: "$eventAt",
    timezone:
      "America/New_York"
  }
}

Local ms value

Examples Gallery

Extract millisecond values from high-precision timestamps, filter sub-second windows, and break timestamps into components.

📚 High-Precision Metrics

Use a metrics collection and extract milliseconds from recordedAt.

Sample Input Documents

Suppose you have a metrics collection with sub-second timestamps:

mongosh
[
  {
    "_id": ObjectId("609c26812e9274a86871bc6a"),
    "event": "api_call",
    "recordedAt": ISODate("2024-06-15T14:30:45.123Z")
  },
  {
    "_id": ObjectId("609c26812e9274a86871bc6b"),
    "event": "api_call",
    "recordedAt": ISODate("2024-06-15T14:30:45.987Z")
  },
  {
    "_id": ObjectId("609c26812e9274a86871bc6c"),
    "event": "api_call",
    "recordedAt": ISODate("2024-06-15T14:30:46.050Z")
  }
]

Example 1 — Add millisecond with $millisecond

Extract the millisecond component from each timestamp:

mongosh
db.metrics.aggregate([
  {
    $project: {
      event: 1,
      recordedAt: 1,
      ms: { $millisecond: "$recordedAt" }
    }
  }
])

How It Works

  • 14:30:45.123Z → millisecond 123.
  • 14:30:45.987Z → millisecond 987.
  • 14:30:46.050Z → millisecond 50 (new second, ms resets).

📈 Practical Patterns

Sub-second filtering, timestamp breakdowns, and timezone-aware extraction.

Example 2 — Filter Events in the First 100 ms of a Second

Find metrics that fired within the first 100 milliseconds of their second:

mongosh
db.metrics.find({
  $expr: {
    $lt: [
      { $millisecond: "$recordedAt" },
      100
    ]
  }
})

How It Works

Combine $millisecond with comparison operators inside $expr. This pattern helps analyze events that cluster at the start of each second.

Example 3 — Full Time Component Breakdown

Extract hour, minute, second, and millisecond together:

mongosh
db.metrics.aggregate([
  {
    $project: {
      event: 1,
      recordedAt: 1,
      timeParts: {
        hour: { $hour: "$recordedAt" },
        minute: { $minute: "$recordedAt" },
        second: { $second: "$recordedAt" },
        millisecond: {
          $millisecond: "$recordedAt"
        }
      }
    }
  }
])

How It Works

For 14:30:45.123Z, you get hour: 14, minute: 30, second: 45, millisecond: 123. Combine these operators to build custom time formats or debugging output.

Example 4 — Millisecond in a Specific Timezone

Extract milliseconds using Eastern Time rather than UTC:

mongosh
db.metrics.aggregate([
  {
    $project: {
      event: 1,
      recordedAt: 1,
      msUtc: {
        $millisecond: "$recordedAt"
      },
      msEastern: {
        $millisecond: {
          date: "$recordedAt",
          timezone: "America/New_York"
        }
      }
    }
  }
])

How It Works

The object form with timezone converts the instant to the specified zone before extracting milliseconds. UTC and local values may differ when the local second boundary does not align with UTC.

Bonus — Group by Millisecond for Burst Detection

See which millisecond slots within a second see the most events:

mongosh
db.metrics.aggregate([
  {
    $group: {
      _id: {
        $millisecond: "$recordedAt"
      },
      count: { $sum: 1 }
    }
  },
  { $sort: { count: -1 } }
])

How It Works

Grouping by $millisecond shows distribution within each second across all documents. Useful for spotting burst patterns in high-frequency telemetry.

🚀 Use Cases

  • Sub-second logging — inspect or filter events by millisecond precision.
  • Latency analysis — combine with $subtract for full elapsed ms between timestamps.
  • High-frequency metrics — group or sort bursts within the same second.
  • Debugging timestamps — break dates into hour, minute, second, and millisecond parts.

🧠 How $millisecond Works

1

MongoDB resolves the date

The input expression is evaluated per document — a field, $$NOW, or literal ISODate.

Input
2

$millisecond extracts ms

MongoDB reads the millisecond component as an integer 0–999 within the current second.

Extract
3

An integer is returned

The number is ready for $match, $group, or fine-grained analysis.

Output
=

Sub-second precision

Combine with $second, $minute, and $hour for complete time breakdowns.

Conclusion

The $millisecond operator extracts the millisecond portion of BSON dates in MongoDB aggregation pipelines. It is the right tool when you need sub-second precision within each second, not full elapsed time between dates.

Remember it returns 0–999, uses UTC by default, and supports an optional timezone. Next in the series: $minute.

💡 Best Practices

✅ Do

  • Use $millisecond for sub-second components within a second
  • Combine with $second and $minute for full breakdowns
  • Use $subtract for elapsed milliseconds between two dates
  • Pass timezone when local second boundaries matter
  • Store dates as BSON Date type for reliable extraction

❌ Don’t

  • Expect $millisecond to return a full Unix timestamp in ms
  • Use it on string dates without converting to Date first
  • Assume millisecond values persist across seconds (they reset each second)
  • Confuse $millisecond with $mod on a timestamp
  • Forget UTC default when comparing to local-time business rules

Key Takeaways

Knowledge Unlocked

Five things to remember about $millisecond

Use these points when working with sub-second date precision in MongoDB.

5
Core concepts
📝 02

One Date Arg

Field or ISODate.

Syntax
🛠 03

UTC Default

Timezone optional.

Timezone
🔄 04

Not Elapsed ms

Use $subtract.

Edge case
📑 05

Date Family

$second, $minute.

Related

❓ Frequently Asked Questions

$millisecond returns an integer from 0 to 999 representing the millisecond portion of a BSON Date within the current second. For example, .123 seconds returns 123.
Simple form: { $millisecond: <dateExpression> }. With timezone: { $millisecond: { date: <dateExpression>, timezone: <tz> } }. Pass a field like "$recordedAt" or a literal ISODate.
By default, $millisecond uses UTC. To extract milliseconds in a specific timezone's local time, use the object form with a timezone string like "America/New_York".
$millisecond returns 0–999 (fraction of the second). $second returns 0–59. $minute returns 0–59. Together they break a timestamp into fine-grained parts.
$millisecond is available in MongoDB 3.4 and later in aggregation pipelines and update pipelines that use aggregation expressions.

Continue the Operator Series

Move on to $minute for minute extraction, or review $hour for hour-of-day analysis.

Next: $minute →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

5 people found this page helpful