rajeshpanwar
rajeshpanwar

Reputation: 1233

How to add property to object in array(containing object)?

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.

Upvotes: 8

Views: 7005

Answers (1)

Neil Lunn
Neil Lunn

Reputation: 151112

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.

Upvotes: 9

Related Questions