Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 318
rajeshpanwar Avatar asked Apr 16 '14 11:04

rajeshpanwar


1 Answers

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.

like image 156
Neil Lunn Avatar answered Nov 15 '22 17:11

Neil Lunn