MetaCoder
MetaCoder

Reputation: 478

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()

Upvotes: 1

Views: 975

Answers (1)

Gibbs
Gibbs

Reputation: 22974

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.

Upvotes: 1

Related Questions