Kamlesh Kanazariya
Kamlesh Kanazariya

Reputation: 1269

Round decimal to nearest integer in MongoDB aggregation framework

I have gone through below site but Can't get my solution. Round to 2 decimal

I have below decimals and want to round to nearest integer:

34.56 => 35
34.67 => 35
34.12 => 34

I have tried this:

            "$subtract": [
                        "$x",
                        { "$mod": ["$x", 1] }
                    ]

Same like in Oracle Round function

How can I do in MongoDB?

Upvotes: 1

Views: 2687

Answers (1)

mickl
mickl

Reputation: 49985

MongoDB is introducing $round in 4.2. As a workaround you can use $floor and $ceil conditionally checking if the fraction part is greater that 0.5

db.collection.aggregate([
    {
        $project: {
            x: { 
                $cond: [ 
                    { $gte: [ { $subtract: [ "$x", { $floor: "$x" } ] }, 0.5 ] }, 
                    { $ceil: "$x" }, 
                    { $floor: "$x" } 
                ] 
            }
        }
    }
])

Mongo playground

Upvotes: 5

Related Questions