MongoDB: Using $mod operator to query documents using modulo operation

Updated: February 3, 2024 By: Guest Contributor Post a comment

Introduction

MongoDB has gained immense popularity as a NoSQL database due to its ease of use, dynamic schema, and powerful querying capabilities. Among its various features, one of the notable operators is the $mod operator, which allows you to perform modulo operations on the field values of documents. This tutorial will walk you through the use of the $mod operator in MongoDB, showing you how to leverage modulo operations to filter and query documents effectively. We will progress from basic to advanced examples, enriching your mastery of querying with MongoDB.

Understanding the $mod Operator

The $mod operator in MongoDB is used for selecting documents where a specific field, when divided by a divisor, has a specified remainder. If you have experience with modular arithmetic from mathematics, you’ll find this concept familiar. The syntax for using the $mod operator in a query is as follows:

{
  field: {
    $mod: [divisor, remainder]
  }
}

This matches documents where the value of field, when divided by divisor, has a remainder equal to remainder. Now let’s see some practical examples.

Basic Example

Suppose we have a collection called numbers that stores documents where each document has a field value representing a numeric value. We want to find all the documents where the value is even. In modular arithmetic, a number is even if it is divisible by 2 without any remainder. The MongoDB query for this will look like:

db.numbers.find({
  value: {
    $mod: [2, 0]
  }
})

This query will return all documents with a value field that is an even number. For example, it would match documents such as { value: 2 }, { value: 4 }, but not { value: 3 }.

Filtering by Modulo Criteria

Now let’s say we want to find documents where the value is divisible by 3 with a remainder of 1. This is how the query would look:

db.numbers.find({
  value: {
    $mod: [3, 1]
  }
})

The above query would match documents with values like 4, 7, 10, etc.

Using $mod with Other Query Operators

MongoDB allows you to use the $mod operator in combination with other query operators to create more complex filters. Let’s say you want to find documents where the value is divisible by 4 and the value is greater than 20:

db.numbers.find({
  value: {
    $gt: 20,
    $mod: [4, 0]
  }
})

This will match documents with value as 24, 28, 32, and so on, but not 16 or 20. Combining $gt (greater than) with $mod allows us to narrow down our search criteria effectively.

Index Usage with $mod

An important aspect of querying in MongoDB involves understanding how the query might interact with indexes you may have created. For the most part, when using the $mod operator, indexes won’t be used during the search unless the $mod query is part of a compound index or the query includes criteria that can use an index.

To alleviate potential performance issues with a large dataset, a possible strategy could be creating a separate boolean field that indicates whether a number satisfies a particular modulus condition, and then index that field for faster queries.

Advanced Examples

Let’s delve into more sophisticated examples where we use the $mod operator in conjunction with aggregation pipelines.

db.numbers.aggregate([
  { $match: { value: { $mod: [5, 0] } } },
  { $group: { _id: null, count: { $sum: 1 } } }
])

This aggregation pipeline counts the number of documents in the collection whose value field is divisible by 5 with no remainder. The $match stage filters the documents, while the $group stage tallies them.

You can also perform more complicated operations such as filtering a subset of documents based on the $mod condition within the $project stage:

db.sales.aggregate([
  { $project: {
      items: {
        $filter: {
          input: "$items",
          as: "item",
          cond: { $eq: [{ $mod: ["$item.quantity", 4] }, 0] }
        }
      }
    }
  }
])

This pipeline will project a new field items, but only include those items in each document’s array where the quantity is evenly divisible by 4.

Conclusion

In summary, the $mod operator in MongoDB is a powerful tool for effectively querying documents based on modular arithmetic. By mastering its usage alongside other query and aggregation operators, you can filter and analyze data with a high degree of specificity and efficiency. This tutorial has provided a basis for your journey with MongoDB’s $mod operator and offered solutions for a range of querying needs.