MongoDB

MongoDB $round

While working with numerical values, we came across many decimal values containing 1 or more floating points at the end. In Mathematics, we can convert the float values to make them a whole value by rounding off the float points after the “dot”. There are certain rules to round off decimal point values i.e., can only be round-off to its next consecutive value if the float-point value after the dot is “5”. While working with MongoDB, you might come across decimal values and want to convert them to whole numbers. To do so, MongoDB provides us with the “round” operator to use within the aggregate function. In this guide, we will see how we can use it.

Create Database Collection

We have started the MongoDB shell and displayed all the available databases via the “show dbs” query of MongoDB. The output of this instruction shows 3 built-in databases while the dummy database “test” is already being utilized.

test> show dbs

admin 40.00 KiB

config 72.00 KiB

local 72.00 KiB

If you want to use a specific database, run the “use” instruction along with the database name and you will be using the particular database in a moment.

test> use test

already on db test

Now that we are done moving within the working space of the “test” database, we are allowed to create collections in it. Therefore, we are going to create a collection named “Order” within this “test” database by the use of the “createCollection” function in the instruction. The query for creating a collection along with its output has been demonstrated below.

test> db.createCollection("Order")

{ ok: 1 }

To get all the collections of the “test” database listed on the MongoDB shell, use the displayed query and you will get the collection “Order” listed there as well.

test> show collections

Order

Insert Documents to Collection

After the collection “Order” has been generated, we cannot leave it empty as we have to work on decimal points to utilize the round operator of MongoDB. Therefore, we need to insert at least one field that contains decimal point values in it. So, we have been trying the insertMany function in the instruction preceded by the name of a collection “Order” to insert a total of 3 documents. Each document contains 3 fields i.e., the “Title” field of string type, the “price” field of integer type, and the “tax” field of float type. The Tax field contains values with 1 or more floating points.

test> db.Order.insertMany([{ Title: "Pizza", Price: 4500, Tax: 99.5 },
... {Title: "Burger", Price: 4200, Tax: 49.56}, {Title: "Platter", Price: 3900, Tax: 55.25}])
{
  acknowledged: true,
  insertedIds: {
    '0': ObjectId("63b5a193639e00f0b5c51fae"),
    '1': ObjectId("63b5a193639e00f0b5c51faf"),
    '2': ObjectId("63b5a193639e00f0b5c51fb0")
  }
}

After inserting these 3 documents into the “Order” collection of the database, we will be displaying these on the MongoDB console and have a clear look at them. For this, we will be casting off the “find” function of MongoDB preceded by the name of a collection “Order” in the instruction. Use curly brackets “{}” within the argument to display this collection’s all documents without specifying one. The output for this instruction has been displaying a total of 3 documents beneath.

test> db.Order.find({})
[
  {
    _id: ObjectId("63b5a193639e00f0b5c51fae"),
    Title: 'Pizza',
    Price: 4500,
    Tax: 99.5
  },
  {
    _id: ObjectId("63b5a193639e00f0b5c51faf"),
    Title: 'Burger',
    Price: 4200,
    Tax: 49.56
  },
  {
    _id: ObjectId("63b5a193639e00f0b5c51fb0"),
    Title: 'Platter',
    Price: 3900,
    Tax: 55.25
  }
]

Example # 01:

Now that we are done with the prerequisites and setting up the database, we are going to use the round operator in MongoDB shell instruction to convert the decimal values to whole numbers. As we only have a “Tax” field that contains the decimal values, we will be applying the round operator on it only. To use the round operator, we must use the aggregate() function of MongoDB in the instruction. This instruction starts its arguments with the operator “project” followed by the round operator.

You can also name the field for output to be displayed for decimal point values i.e., rounded values. Then, the operator “round” must contain the name of a field to be updated along with the total number of decimal points you want it to get rounded off. In our case, we rounded off all “tax” field values by 1 and got the modified values in the output. These values contain 1 decimal point value now: 99.5 to remain 99.5 as it has only 1 decimal point already, 49.56 to 49.6 after rounding off 6, and 55.25 to 55.2.

test> db.Order.aggregate( [ {$project: {roundedvalue: { $round:  ["$Tax", 1] }}} ] )
[
  { _id: ObjectId("63b5a193639e00f0b5c51fae"), roundedvalue: 99.5 },
  { _id: ObjectId("63b5a193639e00f0b5c51faf"), roundedvalue: 49.6 },
  { _id: ObjectId("63b5a193639e00f0b5c51fb0"), roundedvalue: 55.2 }
]

When you run the find() function to see the field “Tax” of all documents, you will see that the records are not updated in the collection because the round operator only works at runtime.

test> db.Order.find({})
[
  {
    _id: ObjectId("63b5a193639e00f0b5c51fae"),
    Title: 'Pizza',
    Price: 4500,
    Tax: 99.5
  },
  {
    _id: ObjectId("63b5a193639e00f0b5c51faf"),
    Title: 'Burger',
    Price: 4200,
    Tax: 49.56
  },
  {
    _id: ObjectId("63b5a193639e00f0b5c51fb0"),
    Title: 'Platter',
    Price: 3900,
    Tax: 55.25
  }
]

If you want to get a whole number instead of one decimal point value, you can use the total number of decimal points “0” in the query. Therefore, we have updated the very same instruction for the “tax” field and replaced 1 with 0. After executing the aggregate function query, we have the whole number values for the field “Tax” of all 3 documents from the “Order” collection i.e., 99.5 to 100, 49.56 to 50, and 55.25 to 55.

test> db.Order.aggregate( [ {$project: {roundedvalue: { $round:  ["$Tax", 0] }}} ] )
[
  { _id: ObjectId("63b5a193639e00f0b5c51fae"), roundedvalue: 100 },
  { _id: ObjectId("63b5a193639e00f0b5c51faf"), roundedvalue: 50 },
  { _id: ObjectId("63b5a193639e00f0b5c51fb0"), roundedvalue: 55 }
]

Now, running the same find() function instruction in the MongoDB shell, we have the same output as we have in the above illustration i.e. no change because the round works at runtime only.

test> db.Order.find({})
[
  {
    _id: ObjectId("63b5a193639e00f0b5c51fae"),
    Title: 'Pizza',
    Price: 4500,
    Tax: 99.5
  },
  {
    _id: ObjectId("63b5a193639e00f0b5c51faf"),
    Title: 'Burger',
    Price: 4200,
    Tax: 49.56
  },
  {
    _id: ObjectId("63b5a193639e00f0b5c51fb0"),
    Title: 'Platter',
    Price: 3900,
    Tax: 55.25
  }
]

Example # 02:

Let us use another way to utilize the round operator in MongoDB shell to round off the decimal point values i.e., pretty same with a little difference in the placement of operators and arguments. Within the aggregate function, you will place the arguments in the same array format starting from the use of the project operator. We are going to use the name of a field to be updated and set its status as “1” to display its actual value residing in the collection right now.

Then, we will add a new field named ‘value” followed by the round operator and the name of a field “Tax” as its argument to make it updated. It will convert all the decimal point values to a whole number after rounding off the decimal points at the end. The output shows the original “Tax” field values along with the updated rounded-off values in the field “value”.

test> db.Order.aggregate( [ {$project: { Tax: 1, value:{ $round:  ["$Tax"] }}} ] )
[
  { _id: ObjectId("63b5a193639e00f0b5c51fae"), Tax: 99.5, value: 100 },
  { _id: ObjectId("63b5a193639e00f0b5c51faf"), Tax: 49.56, value: 50 },
  { _id: ObjectId("63b5a193639e00f0b5c51fb0"), Tax: 55.25, value: 55 }
]

Conclusion

After discussing the concept of rounding off the decimal values in the field of mathematics, we have discussed how the “round” operator of MongoDB can be cast-off to round off values by several points. To clear the use of the round operator in MongoDB, we have demonstrated two examples containing the aggregate function that utilizes the round operator. Using these examples, we have rounded off the values by 1 and 2 points at runtime while we have also seen that the use of the round operator doesn’t modify the actual value in the collection.

About the author

Saeed Raza

Hello geeks! I am here to guide you about your tech-related issues. My expertise revolves around Linux, Databases & Programming. Additionally, I am practicing law in Pakistan. Cheers to all of you.