Reputation: 5946
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 :
Upvotes: 14
Views: 6715
Reputation: 21044
I wanted to convert int to string (the opposite of OP's question).
I'm posting this answer here in case it helps someone. OP wanted $toInt
, but I needed the opposite; $toString
and/or $convert
, but those are too new (MongoDB 4.0)
You can use $substr
as seen here:
...
{ stringifiedInt: { $substr: ['$intProperty', 0, -1] } }
...
If you are looking to convert int to text, consider other options here which is very similar - Use Javascript on query results to .forEach
and/or .map
your results (but then you can't do aggregations)
You could:
.forEach
and/or .map
your results (but then you can't do aggregations)Upvotes: 0
Reputation: 1598
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.
Upvotes: 6