ugotchi
ugotchi

Reputation: 1013

Rounding floats within an aggregate function in PHP?

Is it possible to do this within the $project array using PHP's built in round function?

I try to enclose my output value within the round function to 2 decimal places:

"Energy" => round(array('$multiply' => array("$energy", 10)), 2), 

The output error I get is this:

Type: MongoDB\Driver\Exception\RuntimeException

Code: 16406

Message: The top-level _id field is the only field currently supported for exclusion

File: C:\wamp\www\DRM\vendor\mongodb\mongodb\src\Operation\Aggregate.php Line: 168

Currently I have a separate parsing method which takes care of all the rounding, but what I'd like is to do it within the aggregate function in PHP.

Is this possible? I know MongoDB doesn't have round, but there is an external library for that.

Upvotes: 1

Views: 462

Answers (1)

profesor79
profesor79

Reputation: 9473

there is no runding capabilities for mongo yet.

as per this answer, you could add extra steps to aggregation pipeline to get it rounded - below mongo shell code:

> db.a.save({x:1.23456789})
> db.a.save({x:9.87654321})
> db.a.aggregate([{$project:{ _id:0, 
         y:{$divide:[
              {$subtract:[
                      {$multiply:['$x',100]},
                      {$mod:[{$multiply:['$x',100]}, 1]}
              ]},
              100]}
}}])
{ "y" : 1.23 }
{ "y" : 9.87 }

jira ticket

Upvotes: 1

Related Questions