Problems with $sort in Lab - Bringing it all together

Why $sort does not work.
The $avg formula that I wrote is OK (it looks like OK). It calculates the avgRate, but after I add the $sort stage, I get the error “cant $subtract adouble from a string”.

As the error message suggests - there are now 2 types, double and string ?

Hi,

It looks like the problem is not the sort stage, but the previous one (probably a projection). I would review this part:

{
    $add: [
      1,
      {
        $multiply: [
          9,
          {
            $divide: [
              { $subtract: [<x>, <x_min>] },
              { $subtract: [<x_max>, <x_min>] }
            ]
          }
        ]
      }
    ]
  }

Note that <x>, <x_min> and <x_max> must be numeric values, so do not use double or single quotes for numeric values (indeed they’re constants, except x which is a key that needs to be resolved to its actual value, and hence the key name must be quoted).

José Carlos

I think I’m doing the $subtract stage properly but I’m getting the same error:

$divide: [{$subtract: ["imdb.votes", 5]}, {$subtract: [1521105, 5]}]

@JavierBlanco this thread is 1 year old. It would have probably been better to create your own brand new thread.

In this scenario, there are two reasons for this error:

  1. In your specific case, “imdb.votes” is a string and not a field/expression. It needs to be “$imdb.votes”. Refer to the $subtract documentation for examples.
  2. $imdb.votes contains string values, so you must apply some filter before you run $subtract. Here’s the test for string values:
    db.movies.find({"imdb.votes": {$type: "string"}}).count({_id: {$exists: true}})
2 Likes

Only needed to solve the first issue. Thanks as usual, @007_jb.

:slightly_smiling_face: :+1: