title: How to dynamically $set a subdocument field in mongodb?
body: <p>I've run into a situation where I need to dynamically update the value of a field in a subdocument. The field may or may not already exist. If it doesn't exist, I'd like mongo to create it.</p>
  
  <p>Here's an example document that would be found in my <code>Teams</code> collection, which is used to store members of any given team:</p>
  
  <pre><code>{
    _id : ObjectId('JKS78678923SDFD678'),
    name : "Bob Lawblaw",
    status : "admin",
    options : {
      one : "One",
      two : "Two"
    }
  }
  </code></pre>
  
  <p>And here's the query I'm using (I'm using <a href="https://github.com/mafintosh/mongojs" rel="noreferrer">mongojs</a> as my mongo client) to try and update (or create) a value in the <code>options</code> subdocument:</p>
  
  <pre><code>var projectID = 'JKS78678923SDFD678';
  var key = 'Three';
  var value = 'Three';
  
  Teams.findAndModify({
      query: {
          projectID:mongojs.ObjectId(projectID)
      },
      update: {
          $set : { options[key] : value }
      },
      upsert: true,
      multi: false,
      new: true
  },
  function(error, result, lastErrorObject){
  
      console.log(result);
  
  });
  </code></pre>
  
  <p>But I can't get it to 'upsert' the value.</p>
  
  <p>I also found this similar question, but that method didn't work either:
  <a href="https://stackoverflow.com/questions/12184626/nodejs-mongo-insert-into-subdocument-dynamic-fieldname">Nodejs Mongo insert into subdocument - dynamic fieldname</a></p>
  
  <p>Thanks in advance for any help.</p>