$trunc Operator - (MongoDB Misc)
The $trunc operator is a MongoDB aggregation pipeline operator that returns the nearest integer to a specified number with an optional precision value. In this page, we will discuss the syntax, example, output of the $trunc operator, along with its explanation, use, important points, and summary.
Syntax
{$trunc: <number>, <precision>}
Example
Consider a collection named students with the following documents:
{
"_id" : 1,
"name" : "John",
"grade" : 85.47
}
{
"_id" : 2,
"name" : "Jane",
"grade" : 89.52
}
{
"_id" : 3,
"name" : "Dave",
"grade" : 78.64
}
You can use the $trunc operator to round off the values of the grade field to the nearest integer.
db.students.aggregate([
{
$project: {
_id: 0,
name: 1,
grade: 1,
roundedGrade: { $trunc: [ "$grade", 0 ] }
}
}
])
Output
The above aggregation query returns the following result:
{ "name" : "John", "grade" : 85.47, "roundedGrade" : 85 }
{ "name" : "Jane", "grade" : 89.52, "roundedGrade" : 89 }
{ "name" : "Dave", "grade" : 78.64, "roundedGrade" : 78 }
Explanation
The $trunc operator takes two arguments: a number field and an optional precision value. The precision value specifies the number of digits after the decimal point to round off to. If the precision value is negative, the operator rounds off the integer part of the number.
In the example above, the $trunc operator rounds off the grade field values to the nearest integer using a precision value of 0.
Use
The $trunc operator is useful in situations where you want to eliminate the decimal part of a number. It can be used in combination with other aggregation pipeline stages to perform complex computations and rounding operations.
Important Points
- The $trunc operator is a MongoDB aggregation pipeline operator.
- It rounds off the values of a number field to the nearest integer with an optional precision value.
- The precision value specifies the number of digits after the decimal point to round off to.
- It can be used in combination with other aggregation pipeline stages to perform complex computations and rounding operations.
Summary
In this page, we discussed the $trunc operator in MongoDB. We covered its syntax, example, output, explanation, use, important points, and summary. By using the $trunc operator in your aggregation pipeline queries, you can perform complex calculations and round off numbers to the nearest integer.