title: How to update an array of subdocuments with R mongolite?
body: <p>I am using R mongolite to read and write in a mongo collection with the following structure :</p>
  
  <pre><code>[{_id: 1, name: a, sites: [
    {ref: site_a1},
    {ref: site_a2}
  ]},
  {_id: 2, name: b, sites: [
    {ref: site_b1},
    {ref: site_b2}
  ]},
  {_id: 3, name: c, sites: [
    {ref: site_c1},
    {ref: site_c2},
    {ref: site_c3},
    {ref: site_c4}
  ]}]
  </code></pre>
  
  <p>For a given document of my collection, I want to add some attributes to each site. For example, I would like to update the first document like this:</p>
  
  <pre><code>{_id: 1, name: a, sites: [
    {ref: site_a1, lat: 10, lng: 20},
    {ref: site_a2, lat: 5, lng: 40}
  ]}
  </code></pre>
  
  <p>In mongolite, I am able to get the sites as a dataframe and calculate the wanted attributes:</p>
  
  <pre><code>sites &lt;- db$find(query = '{"name": 1}',
          fields='{"_id": 0, "name": 0}')$sites[[1]]
  loc &lt;- getLatLng(sites)
  # loc is a dataframe with lat and lng for each site
  </code></pre>
  
  <p>But I cannot find a way to update my db. I have tried:</p>
  
  <pre><code>db$update(query = '{"name": 1}',
             update = paste0('{"$push":{"sites": {"$each":',jsonlite::toJSON(loc),'}}}'),
             upsert = FALSE, multiple = FALSE)
  </code></pre>
  
  <p>which unsurprisingly gives me:</p>
  
  <pre><code>{_id: 1, name: a, sites: [
    {ref: site_a1},
    {ref: site_a2},
    {lat: 10, lng: 20},
    {lat: 5, lng: 40}
  ]}
  </code></pre>
  
  <p>Is there a way to update the sites field by adding the new attributes to existing elements of the arry or should I replace the whole sites field with a <code>$set</code>? Thanks for your help.</p>
  
  <p>I guess that my issue is linked to <a href="https://stackoverflow.com/questions/10522347/mongodb-update-objects-in-a-documents-array-nested-updating">this question</a> so I might have to loop over each element of my array...</p>