MongoDB $ceil

In MongoDB, the $ceil aggregation pipeline operator returns the smallest integer greater than or equal to the specified number.

$ceil accepts any valid expression that resolves to a number.

Example

Suppose we have a collection called test with the following documents:

{ "_id" : 1, "data" : 1.5 }
{ "_id" : 2, "data" : 1.01 }
{ "_id" : 3, "data" : -1.5 }
{ "_id" : 4, "data" : -1.01 }
{ "_id" : 5, "data" : 1 }

We can use the $ceil operator to return the ceiling of the data field:

db.test.aggregate(
  [
    { $project: { 
        ceiling: { $ceil: "$data" }
      }
    }
  ]
)

Result:

{ "_id" : 1, "ceiling" : 2 }
{ "_id" : 2, "ceiling" : 2 }
{ "_id" : 3, "ceiling" : -1 }
{ "_id" : 4, "ceiling" : -1 }
{ "_id" : 5, "ceiling" : 1 }

Null Values

Null values return null when using the $ceil operator.

Suppose we add the following document to our collection:

{ "_id" : 6, "data" : null }

Let’s apply the the $ceil operator against that document:

db.test.aggregate(
  [
    { $match: { _id: { $in: [ 6 ] } } },
    { $project: { 
        ceiling: { $ceil: "$data" }
      }
    }
  ]
)

Result:

{ "_id" : 6, "ceiling" : null }

We can see that the result is null.

NaN Values

If the argument resolves to NaN$ceil returns NaN.

Example:

db.test.aggregate(
  [
    { $match: { _id: 1 } },
    { $project: { 
        ceiling: { $ceil: "$data" * 1 }
      }
    }
  ]
)

Result:

{ "_id" : 1, "ceiling" : NaN }

Non-Existent Fields

If the $ceil operator is applied against a field that doesn’t exist, null is returned.

Example:

db.test.aggregate(
  [
    { $match: { _id: 1 } },
    { $project: { 
        ceiling: { $ceil: "$age" }
      }
    }
  ]
)

Result:

{ "_id" : 1, "ceiling" : null }