$ceil Operator - (MongoDB Misc)
The $ceil
operator in MongoDB is a mathematical aggregation operator that rounds a number up to the nearest integer or multiple of a specified power of 10. In this page, we will discuss the syntax, examples, output, explanation, use cases, important points, and summary of the $ceil
operator.
Syntax
The $ceil
operator has the following syntax:
{ $ceil: <numberExpression> }
Here, <numberExpression>
could be any valid expression that evaluates to a numeric value.
Example
Assume we have a collection named students
with the following documents:
{ "_id": 1, "name": "Alice", "score": 75.6 }
{ "_id": 2, "name": "Bob", "score": 83.1 }
{ "_id": 3, "name": "Charlie", "score": 91.8 }
{ "_id": 4, "name": "Dave", "score": 63.7 }
{ "_id": 5, "name": "Eve", "score": 46.2 }
To use the $ceil
operator in an aggregation pipeline to round up the score
field to the nearest integer for each document, we can write:
db.students.aggregate([
{
$project: {
roundedScore: { $ceil: "$score" },
name: 1
}
}
])
The output would be:
{ "_id": 1, "name": "Alice", "roundedScore": 76 }
{ "_id": 2, "name": "Bob", "roundedScore": 84 }
{ "_id": 3, "name": "Charlie", "roundedScore": 92 }
{ "_id": 4, "name": "Dave", "roundedScore": 64 }
{ "_id": 5, "name": "Eve", "roundedScore": 47 }
Explanation
The $ceil
operator rounds up a number to the nearest integer or a specific power of 10. It takes one argument, <numberExpression>
, which should evaluate to a numeric value. The operator returns the smallest integer value that is greater than or equal to <numberExpression>
.
In the above example, we use the $ceil
operator to generate a new field called roundedScore
, which contains the rounded-up score for each student document. We then use the $project
operator to retrieve only the name
and roundedScore
fields in the output.
Use
The $ceil
operator can be used in conjunction with other aggregation framework operators to perform mathematical calculations on numeric fields in MongoDB documents. It is useful when you need to get the next integer or multiple of a specified power of 10 value for a numeric field.
Important Points
- The
$ceil
operator rounds up a number to the nearest integer or a specific power of 10. - It takes one argument,
<numberExpression>
, which should evaluate to a numeric value. - The operator returns the smallest integer value that is greater than or equal to
<numberExpression>
.
Summary
In this page, we discussed the $ceil
operator in MongoDB. We covered the syntax, examples, output, explanation, use cases, important points, and summary of the operator. The $ceil
operator is a useful tool for performing mathematical operations on numeric fields in MongoDB and can be used in conjunction with other operators to create powerful aggregation pipelines.