title: MongoDB - $set to update or push Array element
body: <p>In products collection, i have an Array of recentviews which has 2 fields viewedBy &amp; viewedDate.</p>
  
  <p>In a scenario if i already have a record with <code>viewedby</code>, then i need to update it. For e.g if i have array like this :-</p>
  
  
  
  <pre class="lang-js prettyprint-override"><code>"recentviews" : [ 
          {
              "viewedby" : "abc",
              "vieweddate" : ISODate("2014-05-08T04:12:47.907Z")
          }
      ]
  </code></pre>
  
  <p>And user is <code>abc</code>, so i need to update the above &amp; if there is no record for <code>abc</code> i have to <code>$push</code>.</p>
  
  <p>I have tried <code>$set</code> as follows :-</p>
  
  <pre class="lang-js prettyprint-override"><code>db.products.update( { _id: ObjectId("536c55bf9c8fb24c21000095") },
                      { $set: 
                          { "recentviews": 
                              { 
                                  viewedby: 'abc',
                                  vieweddate: ISODate("2014-05-09T04:12:47.907Z") 
                              }
                          } 
                       }
              )
  </code></pre>
  
  <p>The above query erases all my other elements in Array.</p>