如何在嵌套数组中嵌入新字段

时间:2014-05-10 11:15:08

标签: javascript node.js mongodb

嘿,伙计们,我知道是否有可能在嵌套数组中嵌入新字段?

例如像这样的嵌套数组。

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

是否可以使用名为“score”的新字段更新此嵌套数组?这样的事情。

 "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)
        });
       });

1 个答案:

答案 0 :(得分:1)

db.yourCollection.update({comments:  {$elemMatch:{ name:"john"} } }},{$set:{"comments.$.scores":50}},{multi:true});

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