Why is my mongodb aggregation count being returned as a decimal?

545 Views Asked by At

The following query

db.getCollection("xyzCollection").aggregate(
    [
     { $match:
           { "startDate": { $gte: ISODate("2021-01-21T00:00:00.000+0000") } , "markets": { $exists: true }} 
     },
     { $group: 
           { _id: "$sportName" , "count": { $sum: 1 } }
     },
    ]
)

returns the following output:

{ 
    "_id" : "Ice Hockey", 
    "count" : 138.0
}
{ 
    "_id" : "Basketball", 
    "count" : 141.0
}
{ 
    "_id" : "Cricket", 
    "count" : 14.0
}
{ 
    "_id" : "Volleyball", 
    "count" : 32.0
}
{ 
    "_id" : "Football", 
    "count" : 685.0
}

Why is this? And how can I make it return an int? I'm using Studio 3T 2020.10.1 to execute the query. I have already tried using $toInt (wrapping the "1" or wrapping the " { $sum: 1 } ") but as expected it didn't work - bad syntax.

Thanks.

2

There are 2 best solutions below

0
On

If your query is executed by a javascript runtime (which is what usage of ISODate suggests since this is not an MQL construct), the (same) runtime that is rendering your results only has one numeric type and it's a floating point type.

Use a tool written in/utilizing another language that supports integer types.

3
On

It will return int

Play

You could use $toInt in $project pipeline.

{
 $project: {
   sum: {$toInt :"$count" } 
 } 
}

sample

I think it's due to Robo3t/Studio3t

Thanks @wernfried for the reference to justify the behaviour.