13

The issue I have is making a conversion from a string to an integer in order to create an average. I know to use the $convert in later versions, but I cannot find the correct place to use the $toInt term. I know the conversion using this keyword works on the command line on a single example, but where should I place this within the aggregate framework.

db.my_batch.aggregate([{"$unwind": "$current.Data.x"}, {"$match": {"current.Data.x.Typ": "01", "current.Data.x.Value": {"$lt": "TTTT"}}}, {"$project": {"current.Data.x.Value": 1, "uId":1}}, {"$group": {"_id": null, "ad": {"$avg": {"$toInt": "$current.Data.x.Value"}}}} ])

I get the following response:

2018-07-20T17:19:42.707+0200 E QUERY    [thread1] Error: command failed: {
    "ok" : 0,
    "errmsg" : "Unrecognized expression '$toInt'",
    "code" : 168,
    "codeName" : "InvalidPipelineOperator"
} : aggregate failed :
disruptive
  • 5,687
  • 15
  • 71
  • 135
  • 1
    `$toInt` was added in 4.0 along with `$convert`. – JohnnyHK Jul 20 '18 at 15:35
  • @JohnnyHK for simple cases on 3.2.9 I can execute this: > $toInt: "1" 1. However now when I check the other keywords examples, we find: $toInt: "1.6777" gives 1.6777. No error, but simply does not function as expected. – disruptive Jul 20 '18 at 16:07
  • Perhaps you have a 4.0 Mongo shell, but an old server? Why don't you upgrade your server to the latest version? It has a bunch of security and performance enhancements too! – Nic Cottrell Jul 24 '18 at 19:50
  • You may want to see this answer: https://stackoverflow.com/a/52413303/2724342 – Tan Duong Nov 19 '18 at 11:10

1 Answers1

5

Because $toInt and $convert operators were only added in mongodb 4.0, it is best for you to change field type in database and query after that.

Paulius Venclovas
  • 1,337
  • 1
  • 10
  • 15