mongodb - 如何将 MongoDB 中的字段应用函数更新为现有值?
问题描述
在 MongoDB 3.6 中,我有一个这样的文档集合:
[
{
...
"propertyName": "[\"foo\",\"bar\"]",
...
},
...
]
使用 Mongo shell,我想通过对每个 propertyName 值执行 JSON.parse() 函数来更新每个文档,所以文档看起来像
[
{
...
"propertyName": [
"foo",
"bar"
],
...
},
...
]
我怎样才能做到这一点?我不知道如何访问属性的现有值,也找不到任何使用函数更新值的示例。
解决方案
试试这个:
db.collection.find({}).forEach(function (doc) {
db.collection.updateOne(
{ _id: doc._id },
{ $set: { propertyName: JSON.parse(doc.propertyName) } }
);
})
推荐阅读
- qt - “fxc.exe:没有这样的文件或目录”在 WSL 上编译 Qt 时
- cypress - 如何在赛普拉斯配置文件中引用环境变量?
- r - 使用 LiDR 在激光雷达点云上进行网格划分
- python - 生存分析:concordance_index_censored 的参数(scikit-survival)
- javascript - 如何使用这些限制验证我的输入字段
- arrays - 这个方法的返回类型是切片还是借来的数组?
- javascript - 在追加期间需要帮助重新排列 Google 表格列
- matlab - MATLAB:基于两个变量找到目标值的有效方法
- scipy - 使用 scipy.stats 在 customPDF 类中设置种子
- spring-mvc - 使用 Postman 测试登录 api Spring Security