Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Aggregate Conversion String to Int to with Mongo 3.2.9

Tags:

mongodb

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 :
like image 726
disruptive Avatar asked Jul 20 '18 15:07

disruptive


People also ask

How to convert string to INT in MongoDB?

MongoDB query to convert string to int? To convert string to int, use parseInt () in MongoDB. Let us first create a collection with documents −

What are the arguments of $convert in MongoDB?

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:

How to store double data type in MongoDB?

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'.

What are the aggregation operators available in MongoDB?

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.


1 Answers

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.

like image 191
Paulius Venclovas Avatar answered Nov 05 '22 05:11

Paulius Venclovas