MongoDB - Update or Insert object in array
<p>I have the following collection</p>
<pre><code>{
    &quot;_id&quot; : ObjectId(&quot;57315ba4846dd82425ca2408&quot;),
    &quot;myarray&quot; : [ 
        {
            userId : ObjectId(&quot;570ca5e48dbe673802c2d035&quot;),
            point : 5
        },
        {
            userId : ObjectId(&quot;613ca5e48dbe673802c2d521&quot;),
            point : 2
        },        
     ]
}
</code></pre>
<h3>These are my questions</h3>
<p>I want to push into <code>myarray</code> if <code>userId</code> doesn't exist, it should be appended to <code>myarray</code>. If <code>userId</code> exists, it should be updated to point.</p>
<h3>I found this</h3>
<pre><code>db.collection.update({
    _id : ObjectId(&quot;57315ba4846dd82425ca2408&quot;),
    &quot;myarray.userId&quot; :  ObjectId(&quot;570ca5e48dbe673802c2d035&quot;)
}, {
    $set: { &quot;myarray.$.point&quot;: 10 }
})
</code></pre>
<p>But if <code>userId</code> doesn't exist, nothing happens.</p>
<h3>and</h3>
<pre><code>db.collection.update({
    _id : ObjectId(&quot;57315ba4846dd82425ca2408&quot;)
}, {
  $push: {
      &quot;myarray&quot;: {
          userId: ObjectId(&quot;570ca5e48dbe673802c2d035&quot;),
          point: 10
      }
  }
})
</code></pre>
<p>But if <code>userId</code> object already exists, it will push again.</p>
<p>What is the best way to do this in MongoDB?</p>