title: Mongodb $addToSet array with objects
body: <p>I have the following document</p>
  
  <pre><code>{
    "_id": "A",
    "partsIds": [
      {
        "partId": "B",
        "someOtherField": "value"
      },
      {
        "partId": "C",
        "someOtherField": "value"
      }
    ]
  }
  </code></pre>
  
  <p>Now, what I am trying to achieve is <code>$addToSet</code> to the <code>partsIds</code> array, using the <code>partId</code> field value.</p>
  
  <p>So, what I do is </p>
  
  <p><code>collection.update({ _id: 'A' }, { $addToSet: { partsIds: { partId: 'B' } } }, {upsert: true});</code></p>
  
  <p>This operation adds a new object to <code>partsIds</code> array no matter what.</p>
  
  <p>What I am trying to achieve from this is find if <code>partId === 'B'</code> exists don't add anything, if it doesn't, it adds it to partsIds array.</p>
  
  <p>How can I achieve this using mongodb?</p>
  
  <p>I found this answer <a href="https://stackoverflow.com/questions/33576223/using-mongoose-mongodb-addtoset-functionality-on-array-of-objects">Using Mongoose / MongoDB $addToSet functionality on array of objects</a></p>
  
  <p>But it doesn't solve my problem, since it adds a new document when used with <code>upsert</code>.</p>
  
  <p>The way I approached this to get the desired behavior is the following, but I am wondering if there is a way to fully do this on mongo side in one go.</p>
  
  <pre><code>let doc = collection.findOne({ _id: 'A', 'partsIds.partId': 'B' });
  if (!doc) {
    collection.update({ _id: 'A' }, { $push: { partsIds: { partId: 'B' } } }, { upsert: true });
  }
  </code></pre>