Nisanth Sojan
Nisanth Sojan

Reputation: 1099

MongoDB set a sub item in an array

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'

Upvotes: 2

Views: 338

Answers (1)

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236228

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);

Upvotes: 3

Related Questions