title: mongo add to nested array if entry does not contain two fields that match
body: <p>I have a mongo document that contains an array called history:</p>
  
  <pre><code>{
      "_id" : ObjectId("575fe85bfe98c1fba0a6e535"),
      "email" : "email@address",
      "__v" : 0,
      "history" : [ 
          {
              "name" : "Test123",
              "organisation" : "Rat",
              "field" : 4,
              "another": 3
          }
      ]
  }
  </code></pre>
  
  <p>I want to add fields to each history object or update fields <strong>IF</strong> the name AND organisation match, however if they don't, I want to add a new object to the array with the queried name and organisation and add/update the other fields to the object when necessary.</p>
  
  <p>So:</p>
  
  <p>This query, finds one that matches:</p>
  
  <pre><code>db.users.find({ 
      email:"email@address",
      $and: [
          { "history.name": "Test123", "history.organisation": "Rat"}
      ]
  })
  </code></pre>
  
  <p>However, I'm struggling to get the update/upsert to work IF that combination of history.name and history.organisation dont exist in the array.</p>
  
  <p>What I think I need to do is a :</p>
  
  <p>"If this history name does not equal 'Test123' AND the history organisation does not equal 'Rat' then add an object to the array with those fields and any other field provided in the update query."</p>
  
  <p>I tried this:</p>
  
  <pre><code>db.users.update({ 
      email:"email@address",
      $and: [
          { "history.name": "Test123", "history.organisation": "Rat"}
      ]
  }, {
      history: { name: "Test123"},
      history: { organisation: "Rat"}
  }, {upsert:true})
  </code></pre>
  
  <p>But that gave me <code>E11000 duplicate key error index: db.users.$email_1 dup key: { : null }</code></p>
  
  <p>Any help greatly appreciated.</p>
  
  <p>Thanks community!</p>