首页 > 解决方案 > 如何将 MongoDB 中的字段应用函数更新为现有值?

问题描述

在 MongoDB 3.6 中,我有一个这样的文档集合:

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

使用 Mongo shell,我想通过对每个 propertyName 值执行 JSON.parse() 函数来更新每个文档,所以文档看起来像

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

我怎样才能做到这一点?我不知道如何访问属性的现有值,也找不到任何使用函数更新值的示例。

标签: mongodbmongodb-querymongo-shell

解决方案


试试这个:

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

推荐阅读