强制转换数组MongoDB中对象的属性(字符串到int)

强制转换数组MongoDB中对象的属性(字符串到int),mongodb,mongodb-query,aggregation-framework,Mongodb,Mongodb Query,Aggregation Framework,考虑到对象位于对象数组中,是否有方法在对象内部强制转换属性。数组图像\u列表是文档的属性 我需要将size属性从字符串转换为int 我还需要删除id属性 我所拥有的 { ... other_property: "foo", image_list: [ { id:"fooid", name:"fooname", bucket:"foobucket",

考虑到对象位于对象数组中,是否有方法在对象内部强制转换属性。数组
图像\u列表
是文档的属性

  • 我需要将
    size
    属性从字符串转换为int
  • 我还需要删除
    id
    属性
我所拥有的

{ 
  ...
  other_property: "foo",
  image_list: [
    {
       id:"fooid",
       name:"fooname",
       bucket:"foobucket",
       path:"foopath",
       size:"322300"
    },
    ...more images
  ]
  other_property2: "foo2",
  ...
}
我需要什么

{ 
  ...
  other_property: "foo",
  image_list: [
    {
       name:"fooname",
       bucket:"foobucket",
       path:"foopath",
       size:322300
    },
    ...more images
  ]
  other_property2: "foo2",
  ...
}
到目前为止我试过什么

  • 因为我只需要在
    大小为字符串的文档上执行此操作,所以我尝试了以下方法:

    db.collection.update(   
     {image_list:{$exists:true},"image_list.size":{$type:"string"}},   
     [{$set: {"image_list.$.size": {$toInt: "image_list.$.size"}}}]  
    )
    
错误日志:

WriteResult({
    "nMatched" : 0,
    "nUpserted" : 0,
    "nModified" : 0,
    "writeError" : {
        "code" : 16410,
        "errmsg" : "Invalid $addFields :: caused by :: FieldPath field names may not start with '$'."
    }
})

使用聚合管道更新将不支持数组更新的投影
$
运算符

  • $map
    迭代
    图像列表的循环
  • $toInt
    大小
    字段转换为整数
  • $mergeObjects
    将当前图像对象与更新
    大小
    字段合并
  • $unset
    删除
    id
    字段表单
    image\u列表

db.collection.update({
  image_list: { $exists: true },
  "image_list.size": { $type: "string" }
},
[
  {
    $set: {
      image_list: {
        $map: {
          input: "$image_list",
          in: {
            $mergeObjects: [
              "$$this",
              { size: { $toInt: "$$this.size" } }
            ]
          }
        }
      }
    }
  },
  { $unset: "image_list.id" }
])