$floor Operator - (MongoDB Misc)
The $floor
operator in MongoDB rounds a specified number down to the nearest integer. It returns the rounded number as a double.
Syntax
The $floor
expression has the following syntax:
{ $floor: <number> }
The <number>
can be any valid expression that resolves to a number.
Example
Consider the following MongoDB documents.
{ "_id": 1, "amount": 68.64 }
{ "_id": 2, "amount": 23.1 }
{ "_id": 3, "amount": 19.99 }
Using the $floor
operator we can round the amount
field down to the nearest integer as shown below:
db.collection.aggregate([
{
$project: {
roundedAmount: { $floor: "$amount" }
}
}
])
The above query will produce the following output:
{ "_id": 1, "roundedAmount": 68 }
{ "_id": 2, "roundedAmount": 23 }
{ "_id": 3, "roundedAmount": 19 }
Output
The output generated using $floor
operator returns the rounded number as a double.
Explanation
The $floor
operator is used to round a given number down to the nearest integer. The operator always returns a floating-point number, even if the input number is an integer.
Use
The $floor
operator is most commonly used in aggregation pipelines. It can be used to perform complex calculations involving rounding off fractions, which is useful in financial applications.
Important Points
- The
$floor
operator rounds a given number down to the nearest integer. - The operator always returns a double value, even if the input number is an integer.
- The
$floor
operator is most commonly used in aggregation pipelines.
Summary
In this page, we discussed the $floor
operator in MongoDB. We covered its syntax, example, output, explanation, use, and important points. The $floor
operator is commonly used in financial applications where rounding is necessary to calculate interest, payments, and other values.