强制转换数组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列表
是文档的属性
- 我需要将
属性从字符串转换为intsize
- 我还需要删除
属性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" }
])