Introduction to MongoDB $floor Operator

In MongoDB, the $floor operator is used for rounding down and returning the largest integer less than or equal to the specified number.

Syntax

The syntax for the $floor operator is as follows:

{ $floor: <number> }

Here, <number> is the number to be rounded.

Use Cases

In some cases, it is necessary to perform rounding operations on numerical values in a database, such as rounding to the nearest integer or rounding down. In these situations, the $floor operator can be used.

Examples

The following are two examples demonstrating the use of the $floor operator.

Example 1

Suppose there is a students collection that stores information about student grades. We need to query the average score of each student and round it down to the nearest integer.

Example data:

{ name: "Alice", scores: [75, 85, 90] }
{ name: "Bob", scores: [80, 90, 95] }

Query code:

db.students.aggregate([
  {
    $project: {
      name: 1,
      averageScore: {
        $floor: {
          $avg: "$scores"
        }
      }
    }
  }
])

Query results:

{ "_id": ObjectId("..."), "name": "Alice", "averageScore": 83 }
{ "_id": ObjectId("..."), "name": "Bob", "averageScore": 88 }

Example 2

Suppose there is an orders collection that stores information about order amounts. We need to query the integer part of each order amount.

Example data:

{ orderNo: "202201010001", amount: 85.6 }
{ orderNo: "202201010002", amount: 120.8 }
{ orderNo: "202201010003", amount: 99 }

Query code:

db.orders.aggregate([
  {
    $project: {
      orderNo: 1,
      integerPart: {
        $floor: "$amount"
      }
    }
  }
])

Query results:

{ "_id": ObjectId("..."), "orderNo": "202201010001", "integerPart": 85 }
{ "_id": ObjectId("..."), "orderNo": "202201010002", "integerPart": 120 }
{ "_id": ObjectId("..."), "orderNo": "202201010003", "integerPart": 99 }

Conclusion

This article introduced the $floor operator in MongoDB, which can be used for rounding down and returning the largest integer less than or equal to the specified number. In practical applications, the $floor operator can be used for rounding numerical data to meet different business requirements.