title: MongoDB push item only if it does not exist
body: <p>I have a document with the following fields:  </p>
  
  <pre><code>{
      "id" : 15,
      "existingCodes" : [ 
          {
              "_id" : ObjectId("5c49a6c03a95f50b15409296"),
              "code" : "first"
          }, 
          {
              "_id" : ObjectId("5c49a6c03a95f50b15409295"),
              "code" : "second"
          }, 
          {
              "_id" : ObjectId("5c49a6c03a95f50b15409294"),
              "code" : "third"
          }, 
          {
              "_id" : ObjectId("5c49a6c03a95f50b15409293"),
              "code" : "fourth"
          }
      ]
  }
  </code></pre>
  
  <p>The problem is that I'm trying to push a new object to the <code>existingCodes</code> array but making sure that the <code>code</code> value does not already exist, and every solution that I've tried is not working.</p>
  
  <p>I've tried to achieve this using <code>$push</code> and <code>$ne</code>, but it adds duplicate field:</p>
  
  <pre><code>db.getCollection('codes').update({ id: 15, 'existingCodes.code': { $ne: 'first' } }, { $push: { existingCodes: { code: 'first' } } })
  </code></pre>
  
  <p>But it doesn't add the duplicate field if I change <code>$ne</code> to match "second" or any other existing <code>code</code> value different than "first", and I don't understand why.</p>
  
  <p>I've also tried to use <code>$addToSet</code>:</p>
  
  <pre><code>db.getCollection('codes').update({ id: 15, }, { $addToSet: { existingCodes: { code: 'first' } } })
  </code></pre>