I am trying to update(add if not present) a property to each object in array in mongodb document. For example
My document :
{
"_id" : "1",
student : [
{
"name" : "rajesh",
"rollno" : 1
},
{
name" : "rajesh2",
"rollno" : 2
},
{
name" : "rajesh3",
"rollno" : 3,
class : 6
}
]
}
I want to add property 'class' to all the object in student array. How can I do this in mongodb.
Yes and no.
Provided you know the index of the items in the array this is relatively simple:
db.collection.update(
{ "_id": 1 },
{ "$set": {
"student.0.class": 4,
"student.1.class": 5,
"student.2.class": 6
}}
)
But if you actually wanted to update all of the array values for an unknown length this would not be possible just in single update, so you need to actually retrieve the document and modify the whole array first:
db.collection.find({ _id: 1}).forEach(function(doc) {
for (var i=0; i < doc.student.length; i++) {
doc.student[i] = newValue;
}
db.collection.update(
{ _id: doc._id },
{ "$set": { "student": doc.student } }
);
})
Or some approach basically along those lines.
Know the limitations and code around them appropriately.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With