如何更新 MongoDB 中的字段,将函数应用于现有值?

How to update fields in MongoDB applying function to existing value?

在 MongoDB 3.6 中,我收集了这样的文档:

[
  {
    ...
    "propertyName": "[\"foo\",\"bar\"]",
    ...
  },
  ...
]

使用 Mongo shell,我想通过对每个 属性Name 值执行 JSON.parse() 函数来更新每个文档,因此文档看起来像

[
  {
    ...
    "propertyName": [
      "foo",
      "bar"
    ],
    ...
  },
  ...
]

我该怎么做?我不知道如何访问 属性 的现有值,也找不到任何使用函数更新值的示例。

试试这个:

db.collection.find({}).forEach(function (doc) {
   db.collection.updateOne(
      { _id: doc._id },
      { $set: { propertyName: JSON.parse(doc.propertyName) } }
   );
})