Unable to Parse Integers in updateMany Command

I currently have a collection ‘question’ with a document schema as follows:

 _id: ObjectId("62e32a75a984c054fb986fd0"),
  id: '19',
  product_id: '3',
  body: 'Why is this product cheaper here than other sites?',
  date_written: '1590413602314',
  asker_name: 'jbilas',
  asker_email: 'first.last@gmail.com',
  reported: '0',
  helpful: '6',
  answers: {}```

I am trying to update 'helpful' field to be an integer on every document in my collection. And am running this command:

db.question.updateMany({ }, [{ $set: { helpful: {$toInt: “$helpful”}}}])

And get this error message: 
**MongoServerError:** Failed to parse number 'helpful' in $convert with no onError value: Did not consume whole string.

When I try to update one individually like this, It works successfully. Any tips on what I am doing wrong?

db.question.updateMany({id: “16” }, [{ $set: { helpful: {$toInt: “$helpful”}}}])

Hello @Sam_B1, Welcome to MongoDB Community Forum,

Because some of the documents have alphabets or any special symbols like dot ., You can check the examples in below documentation, when $toInt throws an error,

You can the $convert operator instead of $toInt, because it handles errors and null values, ex:

  • you can pass your desired value in onError property and onNull property, I have passed “null” if it throws an error or null value, both the properties are optional
    $set: { 
      helpful: {
        $convert: {
          input: “$helpful”,
          to: "int",
          onError: null,  // Optional.
          onNull: null    // Optional.

Wow, thank you! If I have my onError property set to null, does that mean it will skip over that instance?

1 Like

No, it will update that value to null value.