I have tried to do this in every possible way, searched through all the resources but could not find a solution to what appears to be a trivial problem.
I have a huge collection imported from elsewhere with a document field
being of string rather than of numeric type. Attempting to do sorting on field
works but naturally does a string sort rather than numeric. Doing a $sum
or $avg
yields 0
and null
respectively.
What I desperately need is a way to $cast
my string field into a numeric value but such feature does not appear to exist. I have tried tricks like $add: ['field', 0]
or $multiply: ['field', 1]
without any success as the arithmetic operators apparently want numeric values. No automatic conversion seems to occur. I have tried this both in $group
and $project
stages to no avail.
If everything else fails, I will have to update my collection by inserting a new numeric field corresponding to my field
but this isn't the preferred solution as the collection will be frequently and fully re-imported from an external source.