如何将所有文档中的部分字段转换为 $toDouble?

How do I Convert a subset of fields in all documents to $toDouble?

我有一个数据库,其中包含许多结构如下的文档:

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 之外的所有文档中的所有字段从字符串转换为双精度。我可以逐个字段执行此操作,但如何批量完成此操作?

您可以尝试从 MongoDB 4.2,

开始的 update with aggregation pipeline 查询
  • $objectToArray 将根文档从对象转换为对象格式的键值数组
  • $map 迭代上述转换数组的循环
  • return k 键原样
  • $cond 检查提供的数组中的键然后不转换意味着忽略和 return 现有值,如果不想转换也可以添加字段名称
  • else $toDouble 将字符串值转换为 double
  • $arrayToObject返回将上面的对象键值数组转换成真实的对象格式
  • $replaceRoot 将上面转换后的对象替换为 root
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" }
                ]
              }
            }
          }
        }
      }
    }
  }]
)

Playground