Working in NodeJS with Mongoose, though the methods are all the same.
So I have documents like (simplified):
{_id: 1, message: 'text1'}
{_id: 2, message: 'text2', reactions: [{_id: autoGen1, user: 'bob', reaction:''},
{_id: autoGen2, user: 'bob', reaction:''}
{_id: autoGen3, user: 'meg', reaction:''}]}
I want to run an update query that finds a message and either
- Adds the reaction if it doesn't exist
- Removes the reaction if it does exist
The user + reaction make a "unique, compound key".
edit
Much testing and experimentation later, I clearly misunderstood how $cond operated and its use-case. Evaluating other options. Open to suggestions.
edit2 Removed my previous, bad attempts. Post was getting too long.
Current Solution: https://mongoplayground.net/p/cgk6qgZ6l9k
Solution based on link in the comments; modified due to array contents.
I really don't like this solution. It's long. It's ugly. Adding an element probably doesn't add the _id. Not an elegant solution overall, in my opinion, unlike the tidy versions linked on SO that deal with primitive arrays and not arrays of objects.
I tried using $elemMatch and $in without success in that playground.