Introduction to MongoDB $toLong Operator

The MongoDB $toLong operator is an operator used to convert a given value to a long data type.

Syntax

The syntax of the $toLong operator is as follows:

{ $toLong: <expression> }

where <expression> is the expression to be converted to a long data type.

Use Cases

In MongoDB, data types are dynamic and different types of values can be stored in a document. Sometimes, we need to convert a value to a long data type for use in aggregation operations. In such cases, the $toLong operator can be used to convert the value to a long data type.

Examples

Here are two examples of using the $toLong operator:

Example 1

Suppose we have the following documents:

{ "score": 95 }
{ "score": "85" }
{ "score": "75.5" }

To calculate the average of the score field of all documents, we can use the following aggregation operation:

db.scores.aggregate([
  {
    $group: {
      _id: null,
      avg_score: { $avg: { $toLong: "$score" } }
    }
  }
])

After running the above aggregation operation, we can get the following result:

{ "_id": null, "avg_score": 85 }

Note that if the $toLong operator is not used, the $avg operation will not be able to calculate the value of the string type.

Example 2

Suppose we have the following documents:

{ "value": NumberLong("9223372036854775807") }
{ "value": "9223372036854775807" }

To convert the value field of all documents to a long data type, we can use the following aggregation operation:

db.values.aggregate([
  {
    $project: {
      long_value: { $toLong: "$value" }
    }
  }
])

After running the above aggregation operation, we can get the following result:

{ "_id": ObjectId("61f86b15f7b1e2d9dc3af3fb"), "long_value": NumberLong("9223372036854775807") }
{ "_id": ObjectId("61f86b15f7b1e2d9dc3af3fc"), "long_value": NumberLong("9223372036854775807") }

Note that if the $toLong operator is not used, string type values will not be able to be converted to long data type.

Conclusion

Using the $toLong operator can convert a given value to a long data type for use in aggregation operations.