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 :
MongoDB query to convert string to int? To convert string to int, use parseInt () in MongoDB. Let us first create a collection with documents −
The arguments can be any valid expression. If unspecified, $convert returns null if the input is null or missing. In addition to $convert, MongoDB provides the following aggregation operators as shorthand when the default "onError" and "onNull" behavior is acceptable:
parseInt () will store double data type in mongodb. Please use new NumberInt (string). in Mongo shell command for bulk usage, yield won't work. Please DO NOT add 'yield'.
In addition to $convert, MongoDB provides the following aggregation operators as shorthand when the default "onError" and "onNull" behavior is acceptable: The following table lists the input types that can be converted to a boolean: No-op. Returns the boolean value. Returns true if not zero. Return false if zero. Returns true if not zero.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With