MongoDB Aggregation .toFixed()

Hello,
I have collection with amount (type: number) as a field. I want 2 decimals to be placed after number in aggregation pipeline. Is there any way to do that in aggregation or any other work around.

Eg: 25.toFixed(2) => ‘25.00’ in javascript.

Hello @sudeep_gujju

you can use $round

{ $round : [ <number>, <place> ] }

or $trunc depending on your needs

{ $trunc : [ <number>, <place> ] }

Cheers,
Michael

1 Like

Both of them are not working.

Before: totalCredit= 5000

Pipeline:
[{$set: {
totalCredit: {$round: [’$totalCredit’, 2]}
}}]

After: totalCredit= 5000

Expected: totalCredit= 5000.00

Hello @sudeep_gujju

Both are working, but you do not want to do formatting in mongodb queries. MQL is not a programming language.
If you really want to do formatting in the query you could convert to a string and use $cond with regex.
I am not adding an example since I really can not suggest use formatting in a query. Trivial things such as formatting are better handled in client code. Part of the NoSQL philosophy in general is to get rid of the API bloat and just focus on the tasks at hand…

This code show how it works, you did found this by your tests.

// Select the database to use.
use('testFormat');

// The drop() command destroys all data from a collection.
db.format.drop();

// Insert a few documents into the format collection.
db.format.insertMany([
{ '_id' : 1, 'totalCredit' : 5000 },
{ '_id' : 2, 'totalCredit' : 5000.005 }
]);

// Run an aggregation
const aggregation = [
    { $project: { roundedValue: { $round: [ "$totalCredit", 2 ] } } }
];
db.format.aggregate(aggregation);

Result:

[
  {
    _id: 1,
    roundedValue: 5000
  },
  {
    _id: 2,
    roundedValue: 5000.01
  }
]