MongoDB 使用 $Convert 无法将 Int64 转换为 Int32

MongoDB Failed to Convert Int64 to Int32 using $Convert

我正在尝试将 mongo 集合中的所有文档转换为当前设置为 Int64 的字段。

当前这是我的文档:

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

如上所述,我想将 numerbOfComments 从 Long (Int64) 更改为 Int32

我尝试过使用多种方法(见下文),但它只是更改了输出中的数据类型,并没有修改数据库中的文档。

谁能帮忙

到目前为止我尝试了什么

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

我也试过这个:

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

您需要使用聚合更新。

playground

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

我在操场上设置了一个错误示例。如果您设置有效值,它将起作用。

请浏览选项部分以更新 one/many 个文档。