Sling Academy
Home/MongoDB/MongoDB: Using $mod operator to query documents using modulo operation

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

Last updated: February 03, 2024

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.

Next Article: MongoDB: Mimic SQL ‘LIKE’ and ‘NOT LIKE’ operators (with examples)

Previous Article: Using MongoDB $jsonSchema to validate documents (with examples)

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)