-1

I have a mongoDB collection like this:

{
    "_id" : ObjectId("54bd056621396c50b6da3d4
    "name" : "Nagaland",
    "districts" : [
            {
                    "name" : "Wokha",
                    "population" : {
                            "2011" : 161223
                    }
            },
            {
                    "name" : "Mokokchung",
                    "population" : {
                            "2011" : 232085
                    }
            },
            {
                    "name" : "Zunheboto",
                    "population" : {
                            "2011" : 153955
                    }
            }
    ]}

Now later I want to add some more attributes to each of the districts like location,sex-ratio etc. How do I do it? When I use update it is adding to the parent not inside a particular district.

Pinaki
  • 473
  • 1
  • 3
  • 14
  • Question duplicate: http://stackoverflow.com/questions/7714216/add-new-field-to-a-collection-in-mongodb – Leonardo Delfino Jan 19 '15 at 16:14
  • @LeonardoDelfino the above link refers to simply adding an attribute to an object which I am able to do but my question was to add it inside one more attribute which is in the form of an array. – Pinaki Jan 21 '15 at 04:25

1 Answers1

1

If you insert static fields in nested documents so below scripts may work

       db.collectionName.find({
   "districts":{"$exists":true}}).forEach(function(data){
    for(var i=0;i<data.districts.length;i++) {
      db.collectionName.update(
     { 
     "_id": data._id, 
     "districts.name": data.districts[i].name 
     },
     {
     "$set": {
       "districts.$.location": "A",
       "districts.$.sex": "M/F",

     }
     },true,true
      );
  }
})
Neo-coder
  • 7,715
  • 4
  • 33
  • 52