大家好,我知道在嵌套数组中增加新字段的可能吗?
例如这样的嵌套数组。
"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});
但是,每个文档的嵌套数组中只有第一个匹配的元素会被修改