Reputation: 2049
Good evening. I have this MongoDB document.
This document contains information about M. Allegri, an italian coach. The array coached_Team contains all teams that Allegri coached. In this example there is just one team, but it's just a test; one coach has a lot of team in coached_Team array.
Is there a way to update the palmarès of just one team?
For example, Juventus last year won 1 Serie A and 1 Coppa Italia.
This query, clearly, does not work because in that array there will be palmarès of all teams that Allegri coached:
db.coach.update({_id:"MA_1967"}, {$set: {"coached_Team.palmarès.Serie A":33}})
So, I thought to use a normalized model instead of denormalized. But I want to know if there is a way to update the palmarés of Juventus, for example, using this denormalized pattern.
Thank you.
Upvotes: 0
Views: 394
Reputation: 2636
Yes you can using the MongoDB positional operator in your update statement. The $
positional operator has some caveats to read up on but you could write your query like this.
db.coach.update({_id:"MA_1967", 'coached_Team': "Juventus"}, {$set: {"coached_Team.$.palmarès.Serie A":33}})
in order to use the $
positional operator you have to include one and only one array attribute in your find. The $
will then match only the first element in the array that matches the document you are looking for. So your update statement reads something like 'set the first item in coached_Team that matched my array query' then you access the palmares and Serie A attribute through the $
positional operator. The $
and elemMatch
operators are very powerful, but unfortunately sometimes very confusing, operators to read up on in MongoDB.
Upvotes: 1