title: MongoDB Collection update: initialize a document with default values
body: <p>I am trying to deal with <em>time series</em> using MongoDB. The common solution adopted by community is to use subdocuments to store information at different level of granularity (see <a href="https://www.mongodb.com/blog/post/schema-design-for-time-series-data-in-mongodb" rel="nofollow noreferrer">
  Schema Design for Time Series Data in MongoDB</a>).</p>
  
  <p>For example, take a look at the following document:</p>
  
  <pre><code>{
    timestamp_minute: ISODate("2013-10-10T23:06:00.000Z"),
    type: “memory_used”,
    values: [
      999999,   // 1 second
      …
      1000000,  // nth second
      1500000,  // n+1th second
      … 
      2000000   // 60th
    ]
  }
  </code></pre>
  
  <p>The document is indexed by minute information and contains a subdocument which store more detailed information for each second.</p>
  
  <p>So far so good. This kind of approach requires an optimization to work properly:</p>
  
  <blockquote>
    <p>Another optimization [..] is preallocating all documents for the upcoming time period; This never causes an existing document to grow or be moved on disk.</p>
  </blockquote>
  
  <p>To implement the above optimization one could use the <code>$setOnInsert</code> property on the <code>update</code> method.</p>
  
  <pre><code>db.getCollection('aCollection').update(
      {
        timestamp_minute: ISODate("2013-10-10T23:06:00.000Z"),
        type: “memory_used”
      },
      {
        $setOnInsert: { values: {'0': 0, '1': 0, '2': 0}},
        $inc: {"values.30": 1}
      },
      { upsert: true }
  )
  </code></pre>
  
  <p>The problem is that it is not possible to use the same field in the same update in two different operation. The above update istruction generates the following error:</p>
  
  <pre><code>Cannot update 'values' and 'values.30' at the same time
  </code></pre>
  
  <p>This problem is tracked on this <a href="https://jira.mongodb.org/browse/SERVER-10711" rel="nofollow noreferrer">issue</a>.</p>
  
  <p><strong>My question is: is there any workaround?</strong> I prefix that I can't use any batch that preallocates empty documents, because I can't know the value of the indexed fields <em>a priori</em> (in the above example, the values of the field <code>type</code>.</p>
  
  <p>Thanks in advance.</p>