
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Get Absolute Value with MongoDB Aggregation Framework
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 }
Advertisements