MongoDB $toLong

From MongoDB 4.0, you can use the $toLong aggregation pipeline operator to convert a value to a long.

Most types can be can be converted to long, but the ObjectId can’t.

When you convert a Date value to a long, $toLong returns the number of milliseconds since the epoch that corresponds to the date value.

When you convert a boolean to a long, if the boolean is true, then the long is 1. If the boolean is false, then the long is 0.

Example

Suppose we have a collection called types and it contains the following documents:

{
	"_id" : ObjectId("601340eac8eb4369cf6ad9db"),
	"double" : 123.75,
	"string" : "123",
	"boolean" : true,
	"date" : ISODate("2020-12-31T23:30:15.123Z"),
	"integer" : 123,
	"long" : NumberLong(123),
	"decimal" : NumberDecimal("123.75")
}

We can use the $toLong operator to convert those fields (except for the _id field) to a long. If the input is already a long, then it simply returns the long.

db.types.aggregate(
  [
    {
      $project:
        { 
          _id: 0,
          double: { $toLong: "$double" },
          string: { $toLong: "$string" },
          boolean: { $toLong: "$boolean" },
          date: { $toLong: "$date" },
          integer: { $toLong: "$integer" },
          long: { $toLong: "$long" },
          decimal: { $toLong: "$decimal" }
        }
    }
  ]
).pretty()

Result:

{
	"double" : NumberLong(123),
	"string" : NumberLong(123),
	"boolean" : NumberLong(1),
	"date" : NumberLong("1609457415123"),
	"integer" : NumberLong(123),
	"long" : NumberLong(123),
	"decimal" : NumberLong(123)
}

Errors

If you encounter errors, try using the $convert operator instead of $toLong. The $convert operator allows you to handle errors without affecting the whole aggregation operation.

The $toLong operator is the equivalent of using the $convert operator to convert a value to a long.

Here’s an example of using $convert to try to convert an ObjectId to a long (which results in an error):

db.types.aggregate(
  [
    {
      $project:
        { 
          _id: 0,
          result: 
          {
            $convert: { 
              input: "$_id", 
              to: "long",
              onError: "An error occurred",
              onNull: "Input was null or empty" 
            }
          }
        }
    }
  ]
)

Result:

{ "result" : "An error occurred" } 

Using $convert allowed us to specify the error message to use when the error occurred, and it didn’t halt the whole aggregation operation.

See MongoDB $convert for more examples.