首页 > 解决方案 > 如何向数组内的现有 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命令?

标签: jsonmongodb

解决方案


试试这个,它会将每个文档中所有作者数组对象的默认值设置为 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}})
})

推荐阅读