title: MongoDB: upsert sub-document
body: <p>I have documents that looks something like that, with a unique index on <code>bars.name</code>:</p>
  
  <p><code>{ name: 'foo', bars: [ { name: 'qux', somefield: 1 } ] }</code></p>
  
  <p>. I want to either update the sub-document where <code>{ name: 'foo', 'bars.name': 'qux' }</code> and <code>$set: { 'bars.$.somefield': 2 }</code>, or create a new sub-document with <code>{ name: 'qux', somefield: 2 }</code> under <code>{ name: 'foo' }</code>.</p>
  
  <p>Is it possible to do this using a single query with upsert, or will I have to issue two separate ones?</p>
  
  <p>Related: <a href="https://stackoverflow.com/questions/10277174/upsert-in-an-embedded-document">&#39;upsert&#39; in an embedded document</a> (suggests to change the schema to have the sub-document identifier as the key, but this is from two years ago and I'm wondering if there are better solutions now.)</p>