0

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.

JL_SO
  • 1,742
  • 1
  • 25
  • 38
  • can you run `explain()` and paste in the output – Minsky Jan 21 '21 at 00:47
  • 1
    See [Data Types in the mongo Shell](https://docs.mongodb.com/manual/core/shell-types/index.html#numberdecimal): *The mongo shell treats all numbers as floating-point values by default.* `$toInt` should work, how did you make it? – Wernfried Domscheit Jan 21 '21 at 08:38
  • was that answer helpful? could you approve/upvote? – Gibbs Jan 28 '21 at 04:47
  • Not really helpful in my case because as stated in the documentation $toInt is "New in version 4.0." I tried and as expected (given I am not on 4.0 - from memory I am on 3.7) it didn't parse. – JL_SO Jan 31 '21 at 21:56

2 Answers2

2

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.

Gibbs
  • 21,904
  • 13
  • 74
  • 138
1

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.

D. SM
  • 13,584
  • 3
  • 12
  • 21