0

I'm working with MongoDB and I wanted to add something to a set, depending on some conditions.

So, say if someone did x then it would add to a set called y, but if someone did y it would add to a set called x.

My first thought was the ternary operator, and I used the following code:

let toAdd = x ? 'y' : 'x'
// Jump cut to $addToSet
$addToSet: {
 toAdd: 'thing'
}

However, this doesn't actually add anything to the database. How could I specify a certain set using a variable?

Adrian Mole
  • 49,934
  • 160
  • 51
  • 83
  • Doesn't it add _anything_? I think it adds _something_ (provided that the rest of the query/configuration is fine) – Sergio Tulentsev Mar 14 '21 at 00:50
  • @SergioTulentsev Nope. Nothing. Checked the database, no new data was added. –  Mar 14 '21 at 00:52
  • are you sure any document was matched to update? What does the update result say how many documents where affected? – Thilo Mar 14 '21 at 00:57
  • @Thilo I'm 100% Positive I'm using an actual document, when I use a regular set, EX `'x'` it updates and everything. –  Mar 14 '21 at 00:59
  • What language is this? Did you mean to make the field name a variable? Then you may have to use something like `$addToSet[toAdd] = 'thing'`. https://stackoverflow.com/q/11508463/14955 – Thilo Mar 14 '21 at 01:02
  • Oh yeah, It is javascript. I'll try that out. –  Mar 14 '21 at 01:03

0 Answers0