MongoDB $millisecond Operator

Beginner
5 min read
Updated: Oct 2026
3 examples
Live preview

What Is $millisecond?

$millisecond is a MongoDB aggregation expression that returns the millisecond portion of a date as an integer from 0 to 999. For …T08:15:39.736Z, the result is 736.

Remember
$millisecond = ms part of a date (0 … 999)

{ $millisecond: <dateExpression> }

{ $millisecond: { date: <date>, timezone: <tz> } }

ISODate("…T08:15:39.736Z") → 736
ISODate("…T00:00:00.000Z") → 0

null / missing → null
string date → pipeline error
UsePrefer
Milliseconds (0–999)$millisecond
Seconds (0–59)$second
Minutes (0–59)$minute

How to Use $millisecond in MongoDB

Pass a BSON date field (or expression), optionally with a timezone.

  1. Choose an expression stage ($addFields or $project).
  2. Pass a Date / Timestamp / ObjectId expression to $millisecond.
  3. Use the short form for UTC, or the document form with timezone when needed.
  4. Combine with $second, $minute, or $hour to break a timestamp into parts.
PieceRequired?Role
$millisecondYesReturns ms 0–999
Date expressionYesDate, Timestamp, or ObjectId
timezoneNoOlson id or UTC offset (default: UTC)

Pseudocode

Pseudocode
for each document:
    d = evaluate(dateExpression)
    if d is null or missing:
        result = null
    else if d is a string:
        error  // aggregation fails
    else:
        result = millisecond part of d   // 0 … 999
    emit { ..., field: result }

Cheat Sheet

Keep these facts handy while extracting milliseconds.

TopicDetail
TypeAggregation expression (not a find filter)
Syntax{ $millisecond: <date> }
Range0 … 999
Input typesDate, Timestamp, ObjectId
Default zoneUTC
Sample…39.736Z → 736
StringsNot allowed — convert first

Live Preview

Watch $millisecond pull the 0–999 part from a timestamp.

Simulates $millisecond (same idea as the mongosh examples below).

Result
date = 2014-01-01T08:15:39.736Z
$millisecond → 736

{ ms: 736 }

Worked Walkthrough — Sale Timestamp

A sale was recorded at 2014-01-01T08:15:39.736Z. We want only the millisecond part.

Calculation
Document:
  { item: "abc", date: ISODate("2014-01-01T08:15:39.736Z") }

Break the time:
  hour        → 8
  minute      → 15
  second      → 39
  millisecond → 736

$millisecond("$date") → 736

Check: .736 seconds = 736 ms ✓

MongoDB Examples

We use a small sales collection. First we extract milliseconds, then break the full clock time into parts. Run these in mongosh after inserting the sample data once.

Example 1 — Sample Data

Imagine two sales with precise timestamps. We save them in a collection named sales.

mongosh
db.sales.insertMany([
  {
    _id: 1,
    item: "abc",
    price: 10,
    quantity: 2,
    date: ISODate("2014-01-01T08:15:39.736Z")
  },
  {
    _id: 2,
    item: "xyz",
    price: 20,
    quantity: 1,
    date: ISODate("2014-01-01T08:15:39.000Z")
  }
]);

How the Data Is Stored in MongoDB

After the insert, MongoDB keeps two documents in sales. Run find() to see them:

mongosh
db.sales.find()

Read one document like this:

Field in MongoDBValue (doc 1)Plain English
_id1Document id
item"abc"Product code
date…39.736ZSale time (BSON Date)

How It Works

  1. Insert once. insertMany adds two sale documents to sales.
  2. Dates are BSON Date. Use ISODate(...), not plain strings.
  3. find() shows the same shape. Ready for $millisecond next.

Example 2 — Extract Milliseconds

Goal: read the 0–999 millisecond portion of each sale’s date.

mongosh
db.sales.aggregate([
  {
    $addFields: {
      ms: { $millisecond: "$date" }
    }
  }
]);

How It Works

  1. Read the stored date. Document 1 has …39.736Z.
  2. Extract ms. $millisecond: "$date" returns 736.
  3. Whole seconds show 0. Document 2 ends in .000, so ms is 0.
  4. Keep all fields. $addFields adds ms next to the original sale data.

Example 3 — Clock Parts Together

Same sales, but project hour, minute, second, and millisecond side by side.

mongosh
db.sales.aggregate([
  {
    $project: {
      item: 1,
      hour: { $hour: "$date" },
      minutes: { $minute: "$date" },
      seconds: { $second: "$date" },
      milliseconds: { $millisecond: "$date" }
    }
  }
]);

How It Works

  1. Same stored dates. Still using the two sale timestamps from Example 1.
  2. Split the clock. $hour, $minute, $second, and $millisecond each take one part.
  3. UTC by default. 08:15:39.736Z → hour 8, minutes 15, seconds 39, ms 736.
  4. $project keeps only listed fields (plus _id unless you turn it off).

Edge Cases & Pitfalls

Check these before using $millisecond in production pipelines.

type

No string dates

Passing "2014-01-01" fails. Store BSON Date, or convert with $toDate / $dateFromString first.

null

Null and missing become null

Missing fields return null, not an error. Handle them before math if nulls are invalid in your data.

range

Result is 0–999, not a duration

$millisecond is the fraction of the current second—not total ms since epoch. Use date math for durations.

vs

Don’t confuse with $second

$second returns 0–59. $millisecond returns 0–999. For …39.736Z, second is 39 and millisecond is 736.

Performance Notes

ApproachCostBest for
$millisecond alonePer-document date mathNeed only the ms part
Several date partsStill O(docs)Hour / minute / second / ms reports
+ timezoneSmall extra conversionLocal calendar views

Date-part expressions are cheap compared with large sorts or joins. Filter early with $match when only some documents need the ms value.

Key Takeaways

  • Role: date → millisecond 0–999.
  • Input: Date / Timestamp / ObjectId (not strings).
  • Sample: …39.736Z → 736.
  • Pair with: $second, $minute, $hour.

One line: $millisecond answers “what is the 0–999 ms part of this date?”—in aggregation.

Frequently Asked Questions

$millisecond returns an integer from 0 to 999 — the millisecond portion of a date within the current second. For ISODate("…T08:15:39.736Z"), it returns 736. Use it inside aggregation expression stages such as $project and $addFields.
Short form: { $millisecond: <dateExpression> }. Document form: { $millisecond: { date: <dateExpression>, timezone: <tz> } }. The date must resolve to a Date, Timestamp, or ObjectId—not a string.
$second returns 0–59 (whole seconds). $millisecond returns 0–999 (the fraction of that second). Together they describe fine-grained time.
Yes by default. Pass timezone (Olson id like "America/New_York" or an offset like "-0400") in the document form when you need a local calendar view. For most offsets, the millisecond value matches UTC.
$millisecond returns null when the input is null or the field is missing. A plain string date causes an aggregation error.
No. Strings like "2014-01-01" cause an error. Store BSON Date / ISODate, or convert first with $toDate / $dateFromString.

Next: $minute

Extract the 0–59 minute portion of a date in aggregation.

$minute tutorial →

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.

9 people found this page helpful