8

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.

2
  • What value is class supposed to have? Commented Apr 16, 2014 at 11:29
  • suppose class value is 7 Commented Apr 16, 2014 at 11:30

1 Answer 1

9

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.

Sign up to request clarification or add additional context in comments.

2 Comments

No, this is only example. The number of object in student is unknown.
@rajeshpanwar I was adding more information while you commented. Consider the the options and decide on which approach is best for you. You can either read the document and determine the length to construct the first form, or just do the second form.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.