Reputation: 3109
hey guys may i know is it possible to upsert new field in a nested array ?
for example a nested array like this.
"comments" : [
{
"name" : "john",
"title" : "Facebook",
"content" : "LOLOLOLOL",
"votes" : {
"up" : [ ],
"down" : [ ]
},
"date" : ISODate("2014-04-24T17:39:49.782Z"),
}
],
is it possible to update this nested array with new field called "scores" ? something like this.
"comments" : [
{
"name" : "john",
"title" : "Facebook",
"content" : "LOLOLOLOL",
"votes" : {
"up" : [ ],
"down" : [ ]
},
"date" : ISODate("2014-04-24T17:39:49.782Z"),
"scores": 50
}
],
i have tried this method but i can't seem to make it works
// 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)
});
});
Upvotes: 1
Views: 843
Reputation: 2917
db.yourCollection.update({comments: {$elemMatch:{ name:"john"} } }},{$set:{"comments.$.scores":50}},{multi:true});
However, only first matched element in nested array for each document would be modified
Upvotes: 1