Sling Academy
Home/MongoDB/Understanding $floor and $ceil operators in MongoDB (with examples)

Understanding $floor and $ceil operators in MongoDB (with examples)

Last updated: February 03, 2024

Introduction

MongoDB is a powerful NoSQL database that offers a variety of operators for manipulating and querying data. Among these, the $floor and $ceil operators play a crucial role in mathematical operations, allowing developers to round down or up numeric values, respectively. In this tutorial, we’ll explore how to use these operators in different scenarios, providing code examples that range from basic to advanced.

Prerequisites

  • Basic understanding of MongoDB
  • MongoDB environment set up for testing
  • Familiarity with MongoDB query and aggregation framework

Understanding $floor and $ceil

Before diving into examples, let’s define what these operators do:

  • $floor: Rounds the given number down to the nearest integer.
  • $ceil: Rounds the given number up to the nearest integer.

Basic Examples

Example 1: Using $floor to Round Down

db.collection.aggregate([
  {
    $project: {
      floorValue: {
        $floor: "$someField"
      }
    }
  }
])

Output:

{
  "floorValue": 2
}

This query rounds down the value in $someField to its nearest integer.

Example 2: Using $ceil to Round Up

db.collection.aggregate([
  {
    $project: {
      ceilValue: {
        $ceil: "$someField"
      }
    }
  }
])

Output:

{
  "ceilValue": 3
}

This query rounds up the value in $someField to its nearest integer.

Intermediate Examples

Example 3: Rounding Sales Figures

In this example, we want to analyze sales figures by rounding them down for conservative estimates and up for optimistic estimates.

Description: We have a collection sales with documents that contain a field amount representing sales amounts in dollars.

Rounding Down (Conservative Estimate)

db.sales.aggregate([
  {
    $project: {
      conservativeEstimate: {
        $floor: "$amount"
      }
    }
  }
])

Output:

{
  "conservativeEstimate": 99
}

Rounding Up (Optimistic Estimate)

db.sales.aggregate([
  {
    $project: {
      optimisticEstimate: {
        $ceil: "$amount"
      }
    }
  }
])

Output:

{
  "optimisticEstimate": 100
}

Advanced Examples

Example 4: Complex Data Transformation

In more complex scenarios, the $floor and $ceil operators can be combined with other aggregation operators for rich data analysis and transformation. Imagine a scenario where you need to calculate monthly budget forecasts, rounding down expenses and rounding up revenues.

db.finances.aggregate([
  {
    $project: {
      month: 1,
      roundedExpense: {
        $subtract: [
          {
            $ceil: "$revenue"
          },
          {
            $floor: "$expense"
          }
        ]
      }
    }
  }
])

Output:

{
  "month": "January",
  "roundedExpense": 150
}

Conclusion

The $floor and $ceil operators in MongoDB offer a nuanced control over numerical data, suitable for a wide range of applications from financial calculations to data cleaning. Through the presented examples, we’ve seen how these operators can be skillfully applied to manipulate data in both simple and complex queries, enhancing the database’s analytical capabilities.

Next Article: MongoDB: Checking if a Field is Array Using $isArray Operator

Previous Article: How to define a JavaScript function within MongoDB shell

Series: MongoDB Tutorials

MongoDB

You May Also Like

  • MongoDB: How to combine data from 2 collections into one
  • Hashed Indexes in MongoDB: A Practical Guide
  • Partitioning and Sharding in MongoDB: A Practical Guide (with Examples)
  • Geospatial Indexes in MongoDB: How to Speed Up Geospatial Queries
  • Understanding Partial Indexes in MongoDB
  • Exploring Sparse Indexes in MongoDB (with Examples)
  • Using Wildcard Indexes in MongoDB: An In-Depth Guide
  • Matching binary values in MongoDB: A practical guide (with examples)
  • Understanding $slice operator in MongoDB (with examples)
  • Caching in MongoDB: A practical guide (with examples)
  • CannotReuseObject Error: Attempted illegal reuse of a Mongo object in the same process space
  • How to perform cascade deletion in MongoDB (with examples)
  • MongoDB: Using $not and $nor operators to negate a query
  • MongoDB: Find SUM/MIN/MAX/AVG of each group in a collection
  • References (Manual Linking) in MongoDB: A Developer’s Guide (with Examples)
  • MongoDB: How to see all fields in a collection (with examples)
  • Type checking in MongoDB: A practical guide (with examples)
  • How to query an array of subdocuments in MongoDB (with examples)
  • MongoDB: How to compare 2 documents (with examples)