Update collection's specific document

I need to find the Document with it’s name field has a given “value”, then find the field named value for this document, this field has an array of documents, find the document with it’s name field has a given value, to this “subDocument” add a new entry “checked”:"checked.

I must have butchered the language but here is my “best” shut.

` RadioOptions.update({name: obj[‘name’], value: [{name: obj[‘value’]}]},{$set: {checked: “checked”}});

`
obj: { name: ‘optionType’, value: ‘1stOption’ }

meteor:PRIMARY> db.radioOptions.find({}).pretty();
obj: { name: ‘optionType’, value: ‘1stOption’ }

meteor:PRIMARY> db.radioOptions.find({}).pretty();
    {
    	"_id" : "QaLW6shWX4jDRzsEW",
    	"name" : "optionType",
    	"value" : [
    		{
    			"name" : "1stOption",
    			"caption" : "1st Option"
                        "checked":  "checked"      <<<< I need to insert this line please
    		},
    		{
    			"name" : "2ndOption",
    			"caption" : "2nd Option"
    		}
    	]
    }

This should work:

db.radioOptions.update({
  name: obj['name'], 
  'value.name': obj['value']
}, {
  $set: {'value.$.checked': true}
});

Check out Mongo docs on the positional operator.

1 Like

that works, thank, I did not foresee another issue, which is remove checked for the other options if found.

Use $unset instead of $set

Which sets the matching element to null.
I assume you did not mean to use it in the posted solution but to write another update?
Can it be done in the same update? and if so, how?

I had a go for no avail. Again bruteforce
RadioOptions.update( {name: obj.name, 'value.name': obj.value}, {$set: {'value.$.checked': true}, $unset: {$nin: {'value.checked': false}}} );

Also tried $ne and $not