title: How can I perform an UPSERT using Azure DocumentDB?
body: <p>Azure DocumentDB does not support UPSERT. Is there a reasonable work around to achieve the same functionality?</p>
  
  <p>Is using a stored procedure which checks if the document exists to determine whether and insert or update should be performed an effective strategy?</p>
  
  <p>What if I need to perform thousands of these in bulk?</p>
  
  <hr>
  
  <p>Vote for the feature here:</p>
  
  <p><a href="http://feedback.azure.com/forums/263030-documentdb/suggestions/7075256-provide-for-upsert" rel="nofollow">http://feedback.azure.com/forums/263030-documentdb/suggestions/7075256-provide-for-upsert</a></p>
  
  <hr>
  
  <p><strong>Update</strong> - Here is my attempt at a bulk upsert stored procedure.</p>
  
  <pre><code>function bulkImport(docs) { 
      var collection = getContext().getCollection(); 
      var collectionLink = collection.getSelfLink(); 
      var count = 0; 
  
      if (!docs) throw new Error('Docs parameter is null'); 
  
      var docsLength = docs.length; 
      if (docsLength == 0) { 
          getContext().getResponse().setBody(0); 
      } 
  
      tryUpsert(docs[count], callback); 
  
      function tryUpsert(doc, callback) {
  
          var query = { query: ""select * from root r where r.id = @id"", parameters: [ {name: ""@id"", value: doc.id}]};
  
          var isAccepted = collection.queryDocuments(collectionLink, query, function(err, resources, options) {
              if (err) throw err;                           
  
              if(resources.length &gt; 0) {
                  // Perform a replace       
                  var isAccepted = collection.replaceDocument(resources[0]._self, doc, callback);     
                  if (!isAccepted) getContext().getResponse().setBody(count);                          
              }
              else {
                  // Perform a create
                  var isAccepted = collection.createDocument(collectionLink, doc, callback);   
                  if (!isAccepted) getContext().getResponse().setBody(count);                             
              }
          });  
  
          if (!isAccepted) getContext().getResponse().setBody(count); 
      }
  
      function callback(err, doc, options) { 
          if (err) throw err; 
  
          // One more document has been inserted, increment the count. 
          count++; 
  
          if (count &gt;= docsLength) { 
              // If we have created all documents, we are done. Just set the response. 
              getContext().getResponse().setBody(count); 
          } else { 
              // Create next document. 
              tryUpsert(docs[count], callback); 
          } 
      } 
  } 
  </code></pre>