MongoDB $ceil Operator

Beginner
5 min read
Updated: Oct 2026
3 examples
Live preview

What Is $ceil?

$ceil is a MongoDB aggregation expression that returns the smallest integer greater than or equal to a number—rounding up toward positive infinity.

Remember
$ceil = Math.ceil for aggregation

{ $ceil: <number expression> }

input  → number (or null / NaN)
output → integer (or null / NaN)

 7.80 → 8
 1    → 1
-2.8  → -2   (toward +∞, not -3)

null / missing → null
NaN → NaN
UsePrefer
Always round up$ceil
Always round down$floor
Nearest value (optional places)$round

How to Use $ceil in MongoDB

Pass a number (or an expression that produces one), then use the integer result in later stages if needed.

  1. Choose an expression stage ($project or $addFields).
  2. Ensure the argument resolves to a number (field, literal, or nested math).
  3. Pass that expression to $ceil to get the ceiling integer.
  4. Optionally combine with $divide for “boxes needed” style math.
PieceRequired?Role
$ceilYesRound up → integer
ExpressionYesNumber, field, or nested math
$divide (etc.)NoBuild a ratio before ceiling

Pseudocode

Pseudocode
for each document:
    x = evaluate(expression)
    if x is null or missing:
        result = null
    else if x is NaN:
        result = NaN
    else:
        result = ceil(x)   // smallest integer ≥ x
    emit { ..., field: result }

Cheat Sheet

Keep these facts handy while writing ceiling expressions.

TopicDetail
TypeAggregation expression (not a find filter)
Syntax{ $ceil: <number> }
DirectionToward +∞ (up the number line)
Positive exampleceil(7.80) → 8
Negative exampleceil(-2.8) → -2
Integer inputUnchanged (ceil(1) → 1)
Boxes pattern$ceil({ $divide: [items, perBox] })

Live Preview

Watch $ceil round a number up. Try a negative value to see rounding toward +∞.

Simulates $ceil (same idea as the mongosh examples below).

Result
x = 4.32
$ceil(x) → 5

{ value: 4.32, ceilingValue: 5 }

Worked Walkthrough — Why -5.34 Becomes -5

Ceiling always moves toward positive infinity. For negatives, that means moving closer to zero—not farther away.

Calculation
Number line (left is smaller):

  …  -6   -5.34   -5   …   4.32   5   …

ceil(4.32)  → 5     (next integer up)
ceil(-5.34) → -5    (next integer up toward +∞)

Not the same as “away from zero”:
  away from zero for -5.34 would be -6  ✗
  $ceil gives -5                     ✓

Check: -5 ≥ -5.34 and is the smallest such integer.

MongoDB Examples

We store three sample numbers (including one negative), apply $ceil, then compute how many boxes an order needs. Run these in mongosh after inserting the sample data once.

Example 1 — Sample Data

Imagine a tiny samples collection with three numbers. One is negative so you can see ceiling toward +∞.

mongosh
db.samples.insertMany([
  { _id: 1, value: 9.25 },
  { _id: 2, value: 4.32 },
  { _id: 3, value: -5.34 }
]);

How the Data Is Stored in MongoDB

After the insert, MongoDB keeps three documents in samples. Run find() to see them:

mongosh
db.samples.find()

Read those documents like this:

Field in MongoDBValuePlain English
_id1 … 3Document id for this lesson
value9.25, 4.32, -5.34Number we will round up
Picture
Expected ceilings:

  9.25  → 10
  4.32  → 5
 -5.34  → -5

We will ask MongoDB for those integers with $ceil.

How It Works

  1. Insert once. insertMany adds three sample documents to samples.
  2. Values are just numbers. Positive and negative decimals are stored as written.
  3. find() shows the same shape. What you inserted is what you get back—ready for $ceil next.

Example 2 — Apply $ceil

Goal: keep the original value and add its ceiling with $project.

mongosh
db.samples.aggregate([
  {
    $project: {
      value: 1,
      ceilingValue: { $ceil: "$value" }
    }
  }
]);

How It Works

  1. Read each value. The pipeline looks at "$value" for every document from Example 1.
  2. Round up. $ceil returns 10, 5, and -5.
  3. Keep the original. $project keeps value and adds ceilingValue.
  4. Negative check. -5.34 becomes -5—up the number line, not down to -6.

Example 3 — Boxes Needed

Practical pattern: 23 items, 10 per box. Partial boxes still need a full box, so use $divide then $ceil.

mongosh
db.orders.insertOne({
  _id: 1,
  items: 23,
  perBox: 10
});

db.orders.aggregate([
  {
    $addFields: {
      boxesNeeded: {
        $ceil: {
          $divide: ["$items", "$perBox"]
        }
      }
    }
  }
]);

How It Works

  1. Insert the order. One document holds items: 23 and perBox: 10.
  2. Divide first. $divide: ["$items", "$perBox"] → 23 / 10 = 2.3.
  3. Ceiling the ratio. $ceil(2.3) → 3 full boxes.
  4. Keep all fields. $addFields adds boxesNeeded next to the originals.

Edge Cases & Pitfalls

Check these before using $ceil in production pipelines.

negatives

Toward +∞, not away from zero

ceil(-2.8) is -2. If you need magnitude-style rounding, combine with $abs carefully—or pick the operator that matches your rule.

null

Null and missing become null

Missing fields return null, not an error. Handle them before math if nulls are invalid in your data.

vs floor

Do not confuse with $floor

$floor rounds down. For 4.32, floor is 4 and ceil is 5.

divide

Avoid divide-by-zero

Box/unit patterns need a non-zero denominator. Guard with $cond or filter bad rows first.

Performance Notes

ApproachCostBest for
$ceil alonePer-document mathRounding stored decimals
$divide + $ceilStill O(docs)Units, boxes, billing partials
vs client-side ceilSame math, less data shippedWhen you need the integer in the pipeline

Ceiling math is cheap compared with large sorts or joins. Filter early with $match when only some documents need rounding.

Key Takeaways

  • Role: smallest integer ≥ the input (round up).
  • Direction: toward +∞ (so -2.8 → -2).
  • Pattern: $ceil(items / perBox) for whole units.
  • Siblings: $floor down, $round nearest.

One line: $ceil answers “what is the next whole number up?”—toward positive infinity, for positives and negatives.

Frequently Asked Questions

$ceil returns the smallest integer greater than or equal to a number—rounding up toward positive infinity. Use it inside aggregation expression stages such as $project and $addFields.
$ceil always rounds toward positive infinity. For example, ceil(-5.34) returns -5, not -6. That moves the value up the number line, closer to zero for negatives.
$ceil rounds up, $floor rounds down, and $round rounds to the nearest value (with optional place). Use $ceil when partial units must always bill or pack as a full unit.
$ceil returns null when the input is null or the field is missing. If the argument is NaN, $ceil returns NaN.
Yes. An integer is already a whole number, so $ceil leaves it unchanged—ceil(1) is 1.
Yes for the math. Think of $ceil as MongoDB’s aggregation version of Math.ceil—run it in the pipeline, not as a standalone find() filter.

Next: $cmp

Compare two values and get -1, 0, or 1 in an aggregation pipeline.

$cmp tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

9 people found this page helpful