json - 如何向数组内的现有 json 记录添加新字段
问题描述
我有如下收藏:
{
"_id" : ObjectId("5b5437c1e8c56c92098f684f"),
"name" : "Mongo",
"authors" : [
{
"id" : 1,
"author" : "jack"
},
{
"id" : 2,
"author" : "mack"
}
]
}
我想edition_year
在作者数组中的每条记录中添加一个新字段,以便我的集合如下所示:
{
"_id" : ObjectId("5b5437c1e8c56c92098f684f"),
"name" : "Mongo",
"authors" : [
{
"id" : 1,
"author" : "jack",
"edition_year" : 2018
},
{
"id" : 2,
"author" : "mack",
"edition_year" : 2017
}
]
}
我必须写什么update
命令?
解决方案
试试这个,它会将每个文档中所有作者数组对象的默认值设置为 0。
db.your_collection.find().forEach(function(doc){
var newAuthors=doc.authors;
newAuthors.forEach(function(author){
//sets default value=0;
author.edition_year=0
});
db.your_collection.update({_id:doc._id},{$set:{authors:newAuthors}})
})
推荐阅读
- git - 在“/feature”文件夹中创建一个分支
- clickhouse - 如何提高 ClickHouse 服务器的启动时间?
- microsoft-graph-api - 如何修复“用户登录”。已为您的租户禁用 Teams。图 api 调用中的错误
- java - 如果未找到实现 bean,则自动装配默认实现
- java - 如何确定小于给定输入值的所有素数?
- decimal - 是否有任何开放的数据库可以让我获得该货币的小数位数?
- reporting-services - MDX 在 MDX 工作室中运行良好。一旦我在 SSRS 中使用它,我就会收到以下错误“查询必须至少有一个轴。第一个轴..”
- c# - 不通过事件调用中断工作流程
- c# - Asp.Net Core 未经授权的登录 - C#
- javascript - 实现撤消功能:如何测量 JavaScript 数组的内存消耗?