title: MongoDB Concurrency Lock Failed for Multithread
body: <p>I did some test on MongoDB from java multithread program to check how MongoDB ensure concurrent access on document. My sample program ensure that only one copy will exists on collection. it inserts a document if it not exists in collection otherwise it updates document frequency. After several tests i found that some documents exists with same value. </p>
  
  <p><strong>Collection Design</strong></p>
  
  <pre><code>{
     _id: ObjectID,
     doc: String,
     doc_freq: Integer
  }
  </code></pre>
  
  <p>Here "doc" field is used for searching and if anything found then "doc_freq" is updated. If nothing is found then new document will be inserted.</p>
  
  <p><strong>Implementation</strong></p>
  
  <pre><code>MongoCollection&lt;Document&gt; collection = mongoDB.getDatabase(DB_NAME).getCollection(COLLECTION);
  
  Document incUpdate = new Document("doc_freq", doc.count());
  
  Document setUpdate = new Document("doc", doc.data());
  
  Document update = new Document();
  update.append("$setOnInsert", setUpdate);
  update.append("$inc", incUpdate);
  
  UpdateOptions updateOptions = new UpdateOptions();
  updateOptions.upsert(true);
  
  Document query = new Document("doc", doc.data());
  
  collection.updateOne(query, update, updateOptions)
  </code></pre>
  
  <p>I have inserted 100000 entries which has same doc value and used 200 thread. And found that more than one entries found on collection with same doc value. I have used <strong>Java MongoDB Driver Version: 3.0.4</strong> and <strong>MongoDB Version:3.2.1</strong> on OS Yosemite</p>