我有一个数据库,其中有许多文档的结构如下:
Date:2021-01-02T08:00:00.000+00:00
FIT_ME44_Volume:"984385"
LT_MJ01:"0"
LT_MJ08:"0"
LT_MJ16:"-34.526024"
FIT_ME56_Volume:"0"
FIT_MJ22_Volume:"9538598"
LT_MJ26:"-61.803848"
FIT_ME52_Volume:"2734271"
LT_ME16:"0"
FIT_MJ28_Volume:"0"
LT_ME29:"2.10552"
LT_ME02:"2.005206"
LT_ME50:"8.732683"
FIT_MJ13_Volume:"0"
FIT_ME02_Volume:"1131376"
FIT_ME23_Volume:"2585415"
LT_ME03:"6.918576"
FIT_MJ08_Volume:"0"
FIT_MJ18_Volume:"0"
QQCr_Total_Plant:"5471052"
FIT_ME03_Volume:"103164"
FIT_ME51_Volume:"3587575"
LT_ME06:"24.423439"
FIT_ME46_Volume:"1619"
我想做的是将除Date
以外的所有文档中的所有字段从字符串转换为double。我可以逐个字段地做,但我如何批量完成呢?
您可以尝试从MongoDB 4.2开始更新聚合管道查询,
$objectToArray
将根文档从对象转换为对象格式的键值数组$map
迭代上述转换数组的循环- 返回
k
键,因为它是 $cond
检查所提供的数组中的键,然后不转换意味着忽略并返回现有值,如果不想转换,您也可以添加字段名- else
$toDouble
将字符串值转换为double $arrayToObject
返回将上述对象的键值数组转换为实际对象格式$replaceRoot
将上述转换对象替换为根
db.collection.updateMany(
{},
[{
$replaceRoot: {
newRoot: {
$arrayToObject: {
$map: {
input: { $objectToArray: "$$ROOT" },
in: {
k: "$$this.k",
v: {
$cond: [
{ $in: ["$$this.k", ["Date", "_id"]] },
"$$this.v",
{ $toDouble: "$$this.v" }
]
}
}
}
}
}
}
}]
)
游乐场