Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
The $pow
operator is used to raise a number to a specified exponent. This can be useful in various scenarios where mathematical computations are required within your documents.
{ $pow: [ <number>, <exponent> ] }
Description | |
---|---|
<number> |
The base number to be raised to the exponent. |
<exponent> |
The exponent to raise the base number to. |
Suppose you want to calculate the square of the fullSales
field in the sales
document.
db.collection.aggregate([
{
$project: {
fullSalesSquare: { $pow: [ "$sales.fullSales", 2 ] }
}
}
])
This output shows that the fullSalesSquare
field contains the square of fullSales
.
[
{ "_id": 1, "sales": { "fullSales": 10 }, "fullSalesSquare": 100 },
{ "_id": 2, "sales": { "fullSales": 20 }, "fullSalesSquare": 400 },
{ "_id": 3, "sales": { "fullSales": 30 }, "fullSalesSquare": 900 }
]
If you want to calculate totalSales
raised to the power of 3 for the "DJ Headphones" category:
db.collection.aggregate([
{
$unwind: "$sales.salesByCategory"
},
{
$match: { "sales.salesByCategory.categoryName": "DJ Headphones" }
},
{
$project: {
totalSalesCubed: { $pow: [ "$sales.salesByCategory.totalSales", 3 ] }
}
}
])
This output shows the totalSales
value raised to the power of 3 for the "DJ Headphones" category:
[
{
"_id": 4,
"category": "DJ Headphones",
"sales": { "salesByCategory": { "totalSales": 5 } },
"totalSalesCubed": 125
},
{
"_id": 5,
"category": "DJ Headphones",
"sales": { "salesByCategory": { "totalSales": 10 } },
"totalSalesCubed": 1000
}
]
- Review options for Migrating from MongoDB to Azure Cosmos DB for MongoDB (vCore)
- Read more about Feature compatibility with MongoDB