Introduction to MongoDB $mod Operator

In MongoDB, the $mod operator is used to calculate the remainder of a given number and compare it with a specified value.

Syntax

The $mod operator has the following format:

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

Where field is the field to be calculated, divisor is the divisor, and remainder is the remainder.

Use Cases

The $mod operator is typically used to query records with a specific remainder, such as querying for even or odd records.

Examples

Example 1

Assuming we have a collection named products that contains the following documents:

{ "_id" : 1, "name" : "Product A", "price" : 10 }
{ "_id" : 2, "name" : "Product B", "price" : 15 }
{ "_id" : 3, "name" : "Product C", "price" : 20 }
{ "_id" : 4, "name" : "Product D", "price" : 25 }
{ "_id" : 5, "name" : "Product E", "price" : 30 }

We can use the $mod operator to find products with even prices:

db.products.find({ price: { $mod: [2, 0] } })

The above query will return the following results:

{ "_id" : 2, "name" : "Product B", "price" : 15 }
{ "_id" : 4, "name" : "Product D", "price" : 25 }

Example 2

Assuming we have a collection named students that contains the following documents:

{ "_id" : 1, "name" : "Alice", "score" : 85 }
{ "_id" : 2, "name" : "Bob", "score" : 90 }
{ "_id" : 3, "name" : "Charlie", "score" : 95 }
{ "_id" : 4, "name" : "David", "score" : 80 }
{ "_id" : 5, "name" : "Emma", "score" : 75 }

We can use the $mod operator to find students with scores that are multiples of 5:

db.students.find({ score: { $mod: [5, 0] } })

The above query will return the following results:

{ "_id" : 2, "name" : "Bob", "score" : 90 }
{ "_id" : 3, "name" : "Charlie", "score" : 95 }
{ "_id" : 5, "name" : "Emma", "score" : 75 }

Conclusion

The $mod operator is a powerful tool for finding records with specific remainders in queries. It is very useful when working with numerical data but should be used with caution as dividing by zero can result in errors.