MongoDB $floor

In MongoDB, the $floor aggregation pipeline operator returns the largest integer less than or equal to the specified number.

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

Example

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

{ "_id" : 1, "data" : 8.99 }
{ "_id" : 2, "data" : 8.01 }
{ "_id" : 3, "data" : -8.99 }
{ "_id" : 4, "data" : -8.01 }
{ "_id" : 5, "data" : 8 }

We can use the $floor operator to return the largest integer less than or equal to the data field:

db.test.aggregate(
  [
    { $project: { 
        data: 1,
        floor: { $floor: "$data" }
      }
    }
  ]
)

Result:

{ "_id" : 1, "data" : 8.99, "floor" : 8 }
{ "_id" : 2, "data" : 8.01, "floor" : 8 }
{ "_id" : 3, "data" : -8.99, "floor" : -9 }
{ "_id" : 4, "data" : -8.01, "floor" : -9 }
{ "_id" : 5, "data" : 8, "floor" : 8 }

In this example, the data field is the original value, and the floor field is the floor of that value.

Null Values

Null values return null when using the $floor operator.

Suppose we add the following document to our collection:

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

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

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

Result:

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

We can see that the result is null.

NaN Values

If the argument resolves to NaN$floor returns NaN.

Example:

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

Result:

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

Non-Existent Fields

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

Example:

db.test.aggregate(
  [
    { $match: { _id: 1 } },
    { $project: { 
        floor: { $floor: "$name" }
      }
    }
  ]
)

Result:

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