$pow (aggregation)

Definition

  • $pow

New in version 3.2.

Raises a number to the specified exponent and returns the result.$pow has the following syntax:

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

The <number> expression can be any valid expression as long as it resolves to a number.

The <exponent> expression can be any valid expression as long as it resolves to a number.

You cannot raise 0 to a negative exponent.

Behavior

The result will have the same type as the input except when itcannot be represented accurately in that type. In these cases:

  • A 32-bit integer will be converted to a 64-bit integer if theresult is representable as a 64-bit integer.
  • A 32-bit integer will be converted to a double if the result isnot representable as a 64-bit integer.
  • A 64-bit integer will be converted to double if the result is notrepresentable as a 64-bit integer.

If either argument resolves to a value of null or refers to a field that ismissing, $pow returns null. If either argument resolves toNaN, $pow returns NaN.

ExampleResults
{ $pow: [ 5, 0 ] }1
{ $pow: [ 5, 2 ] }25
{ $pow: [ 5, -2 ] }0.04
{ $pow: [ -5, 0.5 ] }NaN

Example

A collection named quizzes contains the following documents:

  1. {
  2. "_id" : 1,
  3. "scores" : [
  4. {
  5. "name" : "dave123",
  6. "score" : 85
  7. },
  8. {
  9. "name" : "dave2",
  10. "score" : 90
  11. },
  12. {
  13. "name" : "ahn",
  14. "score" : 71
  15. }
  16. ]
  17. }
  18. {
  19. "_id" : 2,
  20. "scores" : [
  21. {
  22. "name" : "li",
  23. "quiz" : 2,
  24. "score" : 96
  25. },
  26. {
  27. "name" : "annT",
  28. "score" : 77
  29. },
  30. {
  31. "name" : "ty",
  32. "score" : 82
  33. }
  34. ]
  35. }

The following example calculates the variance for each quiz:

  1. db.quizzes.aggregate([
  2. { $project: { variance: { $pow: [ { $stdDevPop: "$scores.score" }, 2 ] } } }
  3. ])

The operation returns the following results:

  1. { "_id" : 1, "variance" : 64.66666666666667 }
  2. { "_id" : 2, "variance" : 64.66666666666667 }