In MongoDB, there isn't a built-in ABS function like in SQL databases. However, you can achieve similar functionality using the $abs operator in aggregation pipelines.
Here's an example:
Suppose you have a collection named numbers with documents containing numeric values:
{ "_id": 1, "value": -10 }
{ "_id": 2, "value": 20 }
{ "_id": 3, "value": -5 }
To get the absolute value of the value field for each document, you can use the $abs operator in an aggregation pipeline like this:
db.numbers.aggregate([
{
$project: {
absoluteValue: { $abs: "$value" }
}
}
])
This aggregation pipeline will produce the following result:
{ "_id": 1, "absoluteValue": 10 }
{ "_id": 2, "absoluteValue": 20 }
{ "_id": 3, "absoluteValue": 5 }
It calculates the absolute value of the value field for each document and includes it in the output as absoluteValue.
No comments:
Post a Comment