Introduction to MongoDB $millisecond Operator

In MongoDB, the $millisecond operator is used to extract the millisecond portion from a date. It can be used with the $project or $addFields stage in an aggregation pipeline. This operator can only be used with fields of the date type.

Syntax

The syntax of the $millisecond operator is as follows:

{ $millisecond: <dateExpression> }

where <dateExpression> represents the date expression from which to extract the millisecond portion and can be one of the following:

  • The name of a date field, such as $dateField.
  • A date value, such as ISODate("2022-03-04T00:00:00.000Z").
  • An expression that returns a date value, such as $toDate.

Use Cases

The $millisecond operator is commonly used in scenarios where precise calculations involving dates are required. For example, when logging response times in a request, the $millisecond operator can be used to extract the millisecond portion of the date for more granular measurement and analysis of response times.

Example

Suppose there is a collection orders that contains information about multiple orders, including order numbers and order times. Now, we need to use the $millisecond operator to extract the millisecond portion of the order time and add it as a new field to each document.

Here is an example of using the $millisecond operator:

Data

db.orders.insertMany([
  { orderNo: "001", orderTime: ISODate("2022-03-04T00:01:23.456Z") },
  { orderNo: "002", orderTime: ISODate("2022-03-04T00:02:34.567Z") },
  { orderNo: "003", orderTime: ISODate("2022-03-04T00:03:45.678Z") }
])

Aggregation Operation

db.orders.aggregate([
  {
    $addFields: {
      orderMillisecond: { $millisecond: "$orderTime" }
    }
  }
])

Result

After executing the above aggregation operation, the following result will be returned:

{ "_id": ObjectId("..."), "orderNo": "001", "orderTime": ISODate("2022-03-04T00:01:23.456Z"), "orderMillisecond": 456 },
{ "_id": ObjectId("..."), "orderNo": "002", "orderTime": ISODate("2022-03-04T00:02:34.567Z"), "orderMillisecond": 567 },
{ "_id": ObjectId("..."), "orderNo": "003", "orderTime": ISODate("2022-03-04T00:03:45.678Z"), "orderMillisecond": 678 }

Conclusion

The $millisecond operator can be used to extract the millisecond portion from a date and can be used in an aggregation pipeline. It is useful in scenarios where more granular calculations involving dates are required.