Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

521
Views
MongoDB Failed to Convert Int64 to Int32 using $Convert

I'm trying to convert all documents in a mongo collection which have a field currently set as Int64 to Int32.

Currently here is my document:

{
       _id: ObjectId("60af668346895440fad766c2"),
       userId: 'xxxxxxxx',
       postName: 'testPost',
       numberOfComments: Long("3"),
       numberOfLikes: Long("6")
     }

As stated above I would like to change numerbOfComments from a Long (Int64) to Int32

I've tried using multiple ways (see below) but it just changes the data type in the output and does not modify the document on the DB.

Can anyone help please

What I've tried so far

db.posts.aggregate(
  [
    {
      $project:
        { 
          result:
          {
            $convert: { 
              input: "$numberOfComments",
              to: "int",
              onError: "An error occurred",
              onNull: "Input was null or empty" 
            }
          }
        }
    }
  ]
)

I've also tried this:

db.posts.aggregate([
      {
        $set: {
          numberOfComments: { toInt: '$numberOfComments' },
        },
      },
    ], {multi: true})
db.posts.updateMany(
  { numberOfComments : { $type: Long } },
  [{ $set: { numberOfComments: { $toInt: "$numberOfComments" } } }],
  { multi: true })

   db.UserProjects.aggregate(
     [
       {
         $project:
           {
             _id: 0,
             numberOfComments: { $toInt: "$numberOfComments" }
           }
       }
     ]
   ).pretty()
over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

You need to use aggregate update.

playground

db.collection.update({
  key: 3 //You can leave empty
},
[ //aggregate update as you need $toInt
  {
    $set: {
      numberOfComments: {
        "$toInt": "$numberOfComments"
      }
    }
  }
])

I set an error example in the playground. If you set a valid value, it will work.

Please explore options part to update one/many documents.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!