Introduction to MongoDB $round Operator

$round is an aggregation operator in MongoDB that rounds a numeric field to a specified number of decimal places. It can be used in aggregation pipelines to round a specified numeric field to the specified decimal place and output the result.

Syntax

The syntax of the $round operator is as follows:

{ $round: { <number>, <place> } }

Here, <number> represents the numeric field to be rounded, which can be a number or an expression that refers to a field. <place> represents the number of decimal places to be retained, which can be a number or an expression that refers to the number of decimal places.

Use cases

The $round operator is usually used in scenarios that require a specified number of decimal places to be retained, such as currency calculations or precision scientific calculations.

Examples

Sample Data

Assume we have a collection named sales containing the following data:

{ _id: 1, product: "A", price: 12.3456 }
{ _id: 2, product: "B", price: 23.4567 }
{ _id: 3, product: "C", price: 34.5678 }

Example 1: Rounding a Number

Suppose we want to round the price field to two decimal places. We can use the following aggregation pipeline:

db.sales.aggregate([
  {
    $project: {
      _id: 0,
      product: 1,
      rounded_price: {
        $round: ["$price", 2]
      }
    }
  }
])

In the above aggregation pipeline, we use $project to exclude the _id field and retain the product and rounded_price fields. The rounded_price field uses the $round operator to round the price field to two decimal places.

Example 2: Referencing Decimal Places with an Expression

Suppose we want to round the price field to three decimal places, but the number of decimal places is stored in another field decimal. We can use the following aggregation pipeline:

db.sales.aggregate([
  {
    $project: {
      _id: 0,
      product: 1,
      rounded_price: {
        $round: ["$price", "$decimal"]
      }
    }
  }
])

In the above aggregation pipeline, we use $project to exclude the _id field and retain the product and rounded_price fields. The rounded_price field uses the $round operator to round the price field to the number of decimal places specified by the decimal field.

Conclusion

The $round operator is an aggregation operator in MongoDB that rounds a number and retains a specified number of decimal places. It is suitable for scenarios that require a specified number of decimal places to be retained, such as currency calculations or scenarios that require high precision.