$sqrt Operator - (MongoDB Misc)
The $sqrt
operator is a mathematical operator supported by MongoDB's aggregation pipeline. It takes a single numerical value as argument and returns the square root of that value.
Syntax
The syntax of the $sqrt
operator is as follows:
{ $sqrt: <number> }
Where <number>
is the numerical value for which you want to calculate the square root.
Example
Given a collection products
with the following documents:
{
_id: 1,
name: "Product A",
price: 100
},
{
_id: 2,
name: "Product B",
price: 64
},
{
_id: 3,
name: "Product C",
price: 225
}
You can use the $sqrt
operator to calculate the square root of the price
field for each document like this:
db.products.aggregate([
{
$project: {
name: 1,
sqrtPrice: { $sqrt: "$price" }
}
}
])
This will produce the following output:
{
"_id" : 1,
"name" : "Product A",
"sqrtPrice" : 10
},
{
"_id" : 2,
"name" : "Product B",
"sqrtPrice" : 8
},
{
"_id" : 3,
"name" : "Product C",
"sqrtPrice" : 15
}
Explanation
The $sqrt
operator calculates the square root of the numeric value provided as argument. Optionally, you can use this operator as part of the $project
stage in the aggregation pipeline to calculate the square roots of field values in each document in a collection.
Use
The $sqrt
operator is useful in situations where you want to perform mathematical operations on numerical data in MongoDB during the aggregation pipeline. You can use it to extract statistical information or to calculate values for use in other fields within a document.
Important Points
- The
$sqrt
operator is used to calculate the square root of a numerical value. - The
$sqrt
operator can be used within the$project
stage of the aggregation pipeline to calculate square roots of field values for each document in a collection. - The
$sqrt
operator can be used in combination with other operators within the aggregation pipeline to perform complex mathematical operations on data in MongoDB.
Summary
In this page, we discussed the $sqrt
operator in MongoDB, which is used to calculate the square root of a numerical value. We discussed the syntax of the operator, provided an example of its use in the aggregation pipeline, explained its functionality and use cases, and listed out some important points for working with this operator. By using the $sqrt
operator, you can perform mathematical operations on numerical data in MongoDB to extract useful information and perform calculations for use in other parts of your application.