2

in the collection

{ _id: 123,
    category: 1,
    desc: 'desc',
    price: 99,
    item: 
     [ { two: '24',
     three: '48' },
       { two: '',
      three:''},
       { two: '33',
      three:'24'},
        ] } ,
{ _id: 121,
    category: 1,
    desc: 'desc',
    price: 99,
    item: 
     [ { two: '24',
     three: '58' },
       { two: '',
      three:''},
       { two: '35',
      three:'54'},
        ] } 

how do i set the value 'two' to null for all record where item.two = '24'

Nisanth Sojan
  • 1,099
  • 8
  • 21

1 Answers1

3

Use positional operator $ to update document from items array which matched search query:

update({ "item.two" : "24" }, 
       { $set : { "item.$.two" : "" }}, false, true);

If you want to remove this field from array documents, then use $unset operator:

update({ "item.two" : "25" }, 
       { $unset : { "item.$.two" : "" }}, false, true);
Sergey Berezovskiy
  • 232,247
  • 41
  • 429
  • 459
  • update({ "item.two" : { $in : ['24','30']} }, { $unset : { "item.$.two" : "" }}, false, true); is not working. can you help me out here. :) and if there are multiple item with two=24 in one collection how can i update it – Nisanth Sojan Nov 01 '13 at 08:30
  • 1
    @NisanthSojan I don't think that update of multiple array items is possible in single query. You can look [here](http://stackoverflow.com/questions/14720734/mongodb-update-multiple-records-of-array) and [here](http://stackoverflow.com/questions/4669178/how-to-update-multiple-array-elements-in-mongodb) for workarounds. – Sergey Berezovskiy Nov 01 '13 at 08:44