I have been attempting to add a new field to each sub-document within all arrays of sub-documents. My script is partially working, but instead of inserting the ordinal_number
into every sub-document, it seems to only be adding it to the first sub-document in each comments
array in the collection.
db.posts.find({
"comments.ordinal_number":{"$exists":true}}).forEach(function(data){
for(var i = 0; i < data.comments.length; i++) {
db.posts.update(
{
"_id": data._id,
"comments.body": data.comments[i].body
},
{
"$set": {
"comments.$.ordinal_number":
1
}
},true,true
);
}
});
output result:
"link" : "cxzdzjkztkqraoqlgcru",
"author" : "machine",
"title" : "arbitrary title",
"comments" : [
{
"body" : "...",
"email" : "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d48ebb869bbda68c9a94a0bc819ab983b98dfab7bbb9">[email protected]</a>",
"author" : "Foo bar",
"ordinal_number" : 1
},
{
"body" : "...",
"email" : "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5431150d200504322e143f020e171e3a31227a373b39">[email protected]</a>",
"author" : "Foo baz"
}
]