Introduction to MongoDB $pow Operator

In MongoDB, the $pow operator can be used to perform exponentiation on a number. It takes two numbers as parameters, the first number is the base and the second number is the exponent, and returns the value of the base raised to the power of the exponent.

Syntax

The syntax of the $pow operator is as follows:

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

where:

  • <number>: the base, which must be a numeric expression.
  • <exponent>: the exponent, which must be a numeric expression.

Use Cases

The $pow operator is typically used in aggregation queries where exponentiation is required, such as computing the square or cube of a field.

Examples

Here are two examples of the $pow operator:

Example 1

Assume we have a students collection that contains the grade information of each student, and we want to calculate the square of each student’s grade. We can use the $pow operator to achieve this:

db.students.aggregate([
  {
    $project: {
      _id: 0,
      name: 1,
      score: 1,
      squaredScore: { $pow: ["$score", 2] }
    }
  }
])

The above aggregation query will return a new document that contains the name of each student, their original grade, and the square of their grade.

Example 2

Assume we have a products collection that contains the price information of each product, and we want to calculate the cube of each product’s price. We can use the $pow operator to achieve this:

db.products.aggregate([
  {
    $project: {
      _id: 0,
      name: 1,
      price: 1,
      cubedPrice: { $pow: ["$price", 3] }
    }
  }
])

The above aggregation query will return a new document that contains the name of each product, their original price, and the cube of their price.

Conclusion

The $pow operator is a very useful operator in MongoDB for performing exponentiation. It can help us compute the square, cube, or other power of a field in aggregation queries, which is very convenient and practical.