Reputation: 1970
Mongodb updates provide the $push
modifier to append to an array. My problem is that i want this to happen on a dict e.g
If my record looks like this initially:
{"collaborations":{'id1':{'role':'dev','scope':'dev'}}}
I want to add another item("id2" below) to the "collaborations" field dict to look something like this:
{"collaborations":{'id1':{'role':'dev','scope':'dev'},'id2':{'role':'qa','scope':'qa'}}}
I am trying with $push
:
my_record.update({match_criteria},{$push,{"collaborations":{'id2':{'role':'qa','scope':'qa'}}}})
and also with $addToSet
:
my_record.update({match_criteria},{$,{"collaborations":{'id2':{'role':'qa','scope':'qa'}}}})
With both of these, mongodb throws as error "Cannot apply $addToSet
($push
) modifier to non-array".
How can this be done for dict types? Any ideas?
Upvotes: 3
Views: 2233
Reputation: 40795
The problem is that $addToSet
and $push
modifiers work with arrays.
To update sub-document (that is what you need here) just use $set
modifier with dot notation to access sub-document (field.subfield
):
my_record.update({
match_criteria
}, {
'$set': {
'collaborators.id2': {
// new document fields here
}
}
})
Upvotes: 7