Update a sub-sub array, mongodb -


my document in collection list:

    {         "_id" : objectid("599a910be15dad0b144363d7"),         "createdat" : isodate("2017-08-21t07:51:39.987z"),         "updatedat" : isodate("2017-08-21t07:51:39.987z"),         "title" : "list",         "maincats" : [              {                 "maincatid" : "1",                 "title" : "cars",                 "_id" : objectid("599a910be15dad0b1443650d"),                 "subs" : [                      {                         "subid" : "1.1",                         "title" : "tires",                         "_id" : objectid("599a910be15dad0b1443653c"),                     }                ]          }       ] } 

the title ("tires") in subs array should updated subid (1.1) criteria.

something like:

db.list.update(     {         '_id' : objectid("599a910be15dad0b144363d7"),         'maincats.subs.subid' : '1.1'     },      {         $set : {             'maincats.subs.title' : 'new title',         }     } ) 

cant work.

you have use positional operator $. unfortunately operator cannot applied twice, cannot traverse sub array. , stands first match of update query cannot use multiple update. if updating 1 sub document need(as far can see in query, have id of sub document) can achive goal redefining data structure below:

{     "_id" : objectid("599a910be15dad0b144363d7"),     "createdat" : isodate("2017-08-21t07:51:39.987z"),     "updatedat" : isodate("2017-08-21t07:51:39.987z"),     "title" : "list",     "categories": [         {             "maincatid" : "1",             "maintitle" : "cars",             "subid" : "1.1",             "subtitle" : "tires"         }     ] } 

and can update 1 document(first matching query) below:

db.test.update( {'_id' : objectid("599a910be15dad0b144363d7"), 'categories.subid': '1.1'}, {     $set : {         'categories.$.subtitle' : 'new title'     } } ) 

Comments

Popular posts from this blog

python - Operations inside variables -

Generic Map Parameter java -

arrays - What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it? -