Get Absolute value with MongoDB aggregation framework?

MongoDBDatabaseBig Data Analytics

You can use $abs operator for this. Let us first create a collection with documents

> db.absoluteValueDemo.insert({"Value":98});
WriteResult({ "nInserted" : 1 })
> db.absoluteValueDemo.insert({"Value":-100});
WriteResult({ "nInserted" : 1 })
> db.absoluteValueDemo.insert({"Value":0});
WriteResult({ "nInserted" : 1 })
> db.absoluteValueDemo.insert({"Value":-9999990});
WriteResult({ "nInserted" : 1 })

Following is the query to display all documents from a collection with the help of find() method:

> db.absoluteValueDemo.find().pretty();

This will produce the following output

{ "_id" : ObjectId("5ca271f56304881c5ce84b9a"), "Value" : 98 }
{ "_id" : ObjectId("5ca271fa6304881c5ce84b9b"), "Value" : -100 }
{ "_id" : ObjectId("5ca271fe6304881c5ce84b9c"), "Value" : 0 }
{ "_id" : ObjectId("5ca2720f6304881c5ce84b9d"), "Value" : -9999990 }

Following is the query to get absolute value with MongoDB aggregation framework

> db.absoluteValueDemo.aggregate({ $project: { AbsoluteValue: { $abs: '$Value' } }});

This will produce the following output

{ "_id" : ObjectId("5ca271f56304881c5ce84b9a"), "AbsoluteValue" : 98 }
{ "_id" : ObjectId("5ca271fa6304881c5ce84b9b"), "AbsoluteValue" : 100 }
{ "_id" : ObjectId("5ca271fe6304881c5ce84b9c"), "AbsoluteValue" : 0 }
{ "_id" : ObjectId("5ca2720f6304881c5ce84b9d"), "AbsoluteValue" : 9999990 }
raja
Published on 12-Apr-2019 14:21:02
Advertisements