Introduction to MongoDB $ceil Operator

The $ceil operator is one of the mathematical operators in MongoDB, used to round a number up to the nearest integer.

Syntax

The syntax of the MongoDB $ceil is as follows:

{ $ceil: <numberExpression> }

Here, <numberExpression> is the numeric expression that needs to be rounded up.

Use Case

The $ceil operator is typically used in scenarios where a number needs to be rounded up, such as when calculating averages in statistical data and rounding up the decimal part to an integer.

Example

Assume there is a students collection that contains information such as the name and score of each student. Now, we need to calculate the average score of each student and round the result up to the nearest integer. This can be achieved using the $ceil operator:

db.students.aggregate([
  {
    $group: {
      _id: "$name",
      avgScore: { $avg: "$score" }
    }
  },
  {
    $project: {
      _id: 0,
      name: "$_id",
      avgScore: { $ceil: "$avgScore" }
    }
  }
])

Assuming the students collection contains the following data:

{ name: "Alice", score: 95 }
{ name: "Bob", score: 82 }
{ name: "Alice", score: 89 }
{ name: "Bob", score: 75 }

Running the above aggregation operation will result in:

{ name: "Alice", avgScore: 92 }
{ name: "Bob", avgScore: 79 }

Here, Alice’s average score is (95 + 89) / 2 = 92, which is rounded up to integer 92; Bob’s average score is (82 + 75) / 2 = 78.5, which is rounded up to integer 79.

Conclusion

The $ceil operator in MongoDB is one of the mathematical operators used to round a number up to the nearest integer. It is typically used in scenarios where a number needs to be rounded up, such as when calculating averages in statistical data and rounding up the decimal part to an integer.