mongo-db
  1. mongo-db-mod-operator

$mod Operator - (MongoDB Misc)

In MongoDB, the $mod operator performs a modulo operation on the first operand and the second operand and returns the remainder. This page covers the syntax, example, output, explanation, use case, important points, and summary of the $mod operator in MongoDB.

Syntax

The basic syntax of using the $mod operator in a MongoDB query is as follows:

{: { $mod: [ divisor, remainder ] } }
  • field: The name of the field for which the operation is to be performed.
  • divisor: The divisor by which the field's value is to be divided.
  • remainder: The value of the remainder from the division.

Example

Consider a collection orders with the following records:

{ "_id" : 1, "item" : "apple", "quantity" : 51 }
{ "_id" : 2, "item" : "banana", "quantity" : 13 }
{ "_id" : 3, "item" : "kiwi", "quantity" : 53 }
{ "_id" : 4, "item" : "orange", "quantity" : 31 }

The following query will return the documents that have a quantity value of 1 when divided by 10:

db.orders.find({quantity:{$mod:[10, 1]}})

The output of this query will be:

{ "_id" : 1, "item" : "apple", "quantity" : 51 }

Output

The $mod operator returns the documents that have a field value equal to the remainder of the specified value. The output will include all the matching documents that meet the specified criteria.

Explanation

The $mod operator performs a modulo operation on the field value and returns the remaining value. A document is considered a match if the value of the field divided by the divisor is equal to the given remainder.

Use

The $mod operator is used to retrieve all documents where the field's value divided by the divisor results in the specified remainder. It is useful when you want to perform basic arithmetic operations on the fields in your documents.

Important Points

  • The $mod operator performs a modulo operation on the field value.
  • The $mod operator returns the remaining value.
  • A document is a match if the value of the field divided by the divisor is equal to the given remainder.

Summary

In this page, we discussed the $mod operator in MongoDB. We covered the syntax, examples, output, explanation, use case, important points, and summary of $mod operator. By using the $mod operator, you can perform simple arithmetic operations on the in your MongoDB documents, making it easier to retrieve the data you need for analysis and decision-making.

Published on: