mongo-db
  1. mongo-db-round-operator

$round Operator - ( MongoDB Misc )

The $round operator is a MongoDB aggregation operator that allows you to round a number to a specified number of decimal places. In this page, we will discuss how to use the $round operator in MongoDB.

Syntax

The $round operator has the following syntax:

{
  $round: {
    <number>: <double>,
    [place: <integer>]
  }
}

Example

Here's a sample sales collection:

{
  "_id": 1,
  "product": "Shampoo",
  "price": 3.49,
  "quantity": 13
},
{
  "_id": 2,
  "product": "Toothbrush",
  "price": 2.79,
  "quantity": 9
},
{
  "_id": 3,
  "product": "Soap",
  "price": 1.99,
  "quantity": 21
}

To use the $round operator, you can use the following query to round the price field to two decimal places:

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

This query returns the following result:

{
  "_id": 1,
  "product": "Shampoo",
  "price": 3.49,
  "quantity": 13
},
{
  "_id": 2,
  "product": "Toothbrush",
  "price": 2.79,
  "quantity": 9
},
{
  "_id": 3,
  "product": "Soap",
  "price": 1.99,
  "quantity": 21
}

Output

The $round operator rounds the specified number to the specified number of decimal places.

Explanation

The $round operator is useful when you need to manipulate numbers in your MongoDB queries. You can use it to round numbers to a specific decimal place.

Use

The $round operator is useful when you need to manipulate numbers in your MongoDB queries. You can use it to round numbers to a specific decimal place. This operator can be used in different aggregation pipeline stages such as $project, $group, and $addFields.

Important Points

  • The $round operator rounds a number to a specified number of decimal places.
  • The $round operator can be used in different aggregation pipeline stages such as $project, $group, and $addFields.

Summary

The $round operator is a useful MongoDB aggregation operator that allows you to round a number to a specified number of decimal places. In this page, we covered the syntax, example, output, explanation, use, and important points of the $round operator.

Published on: