title: MongoDB: upsert with unique index
body: <p>I must say I'm not really a mongoDB expert, but this is what I'm trying to do.</p>
  
  <p>I have an app that would get a feed of "food" objects each time I switch on the app, this feed is received from an external web API service. I can only save the  <strong>unique</strong> "food" ID for each of these objects due to ToS agreement with the external API service.</p>
  
  <p>Now, each time I switch on the app, I would get the feed of food objects and I only want to save the food object ID ("foodId") once in my mongoDB. I have therefore decided to do an upsert each time I open the app. I'm not sure if this is the best way to write the upsert method as you can see the query params and the update params are the same and both relate to the "foodId":</p>
  
  <pre><code>                    Query query = new Query();
                      query.addCriteria(Criteria.where("foodId").in(foodIdfromApi));
                      Update update = new Update();
                      update.set("foodId", foodIdfromApi);
                      mongoTemplate.upsert(query, update, Food.class);
  </code></pre>
  
  <p>Since "foodId" is unique, I have created a unique index on "foodId" </p>
  
  <p>This is from MongoDB:
  <a href="http://docs.mongodb.org/manual/reference/method/db.collection.update/#upsert-option" rel="nofollow">http://docs.mongodb.org/manual/reference/method/db.collection.update/#upsert-option</a></p>
  
  <blockquote>
    <p>To prevent MongoDB from inserting the same document more than once,
    create a unique index on the name field. With a unique index, if
    multiple applications issue the same update with upsert: true, exactly
    one update() would successfully insert a new document.</p>
    
    <p>The remaining operations would either:</p>
    
    <p>update the newly inserted document, or fail when they attempted to
    insert a duplicate. If the operation fails because of a duplicate
    index key error, applications may retry the operation which will
    succeed as an update operation.</p>
  </blockquote>
  
  <p>My app downloads the feed successfully the first time that it ran. But subsequently, it has been giving me the duplicate index key error each time I want to do an upsert (which is each time I open my app).</p>
  
  <blockquote>
    <p>Write failed with error code 11000 and error message 'E11000 duplicate
    key error index</p>
  </blockquote>
  
  <p>I do not want to remove the unique index as then there is a potential that duplicated food objects might exists. How do I get around this issue?</p>