如何在嵌套数组中追加新字段

how to upsert new field in a nested array

本文关键字:新字段 字段 追加 嵌套 数组      更新时间:2023-09-26

嘿,伙计们,我可以知道在嵌套数组中追加新字段吗?

例如像这样的嵌套数组。

"comments" : [
        {
            "name" : "john",
            "title" : "Facebook",
            "content" : "LOLOLOLOL",
            "votes" : {
                "up" : [ ],
                "down" : [ ]
            },
            "date" : ISODate("2014-04-24T17:39:49.782Z"),
        }
    ],

是否可以用名为"分数"的新字段来更新这个嵌套数组?像这样的东西。

 "comments" : [
            {
                "name" : "john",
                "title" : "Facebook",
                "content" : "LOLOLOLOL",
                "votes" : {
                    "up" : [ ],
                    "down" : [ ]
                },
                "date" : ISODate("2014-04-24T17:39:49.782Z"),
                "scores": 50
            }
        ],

我试过这种方法,但我似乎不能使它工作

       // get up vote, down vote to calculate 
    posts.findOne({'comments': { $elemMatch: { permalink: data.permalink } } },function(err, data){
            var ups = data.votes.up.length;
            var downs = data.votes.down.length;
            var marks = favourite(ups,downs);
            var scores = {
                "comments.$.scores":marks
            }
        // insert the scores in a nested array as new field.
    posts.update({'comments': { $elemMatch: { permalink: data.permalink } } },{$set:scores},{upsert:true}, function(err, post) {
            "use strict";
            if (err) console.log(err)
        });
       });
db.yourCollection.update({comments:  {$elemMatch:{ name:"john"} } }},{$set:{"comments.$.scores":50}},{multi:true});

然而,每个文档的嵌套数组中只有第一个匹配的元素会被修改