mongo-db
  1. mongo-db-pow-operator

$pow Operator - ( MongoDB Misc )

In MongoDB, the $pow operator is used to raise a number to a specified exponent. This page will discuss the syntax, examples, output, explanation, use, important points, and summary of $pow operator in MongoDB.

Syntax

The basic syntax of the $pow operator is as follows:

{ $pow: [ <number>, <exponent> ] }

Here, <number> is the base number and <exponent> is the exponent to which <number> is raised.

Example

Let's see an example of the $pow operator in MongoDB. Consider we have a collection named numbers having the following documents:

{ "_id" : 1, "number" : 5 }
{ "_id" : 2, "number" : 6 }
{ "_id" : 3, "number" : 7 }

To return the square of each number in the collection, we can use the following query:

db.numbers.aggregate([
    { $project: { square: { $pow: [ "$number", 2 ] } }}
])

Here, the $project stage is used to add a new field square that contains the square of the number field in each document. The $pow operator is used to raise the number field to the power of 2.

Output

The output of the above query will be:

{ "_id" : 1, "square" : 25 }
{ "_id" : 2, "square" : 36 }
{ "_id" : 3, "square" : 49 }

Explanation

The $pow operator is a mathematical function used to compute the power of a number. It takes two arguments: the base number and the exponent to which the base number is raised.

In MongoDB, the $pow operator is used in the aggregation pipeline to perform mathematical computation on the documents. It can be used in expressions or in an aggregate stage to compute the power of a number.

Use

The $pow operator is used to perform mathematical computation on the documents in MongoDB. It is useful in situations where you need to raise a number to a certain power or perform other mathematical computations in a query.

Important Points

  • The $pow operator is used to raise a number to a certain power in MongoDB.
  • It takes two parameters: the base number and the exponent.
  • The $pow operator can be used in the aggregation pipeline or in an expression.

Summary

In this page, we have discussed the $pow operator in MongoDB. We have covered the syntax, example, output, explanation, use, and important points of the operator. The $pow operator is a useful mathematical function that can perform computations on the documents in a MongoDB collection.

Published on: