title: Atomic if not exist then insert in Mongodb .Net driver
body: <p>Let us say I have the following model:</p>
  
  <pre><code>public class Person
  {
      [BsonId]
      public Guid Id { get; set; }
      public string Name { get; set; }
      public string Title { get; set; }
      public DateTime ReceivedAt { get; set; }
  }
  </code></pre>
  
  <p>And I have N threads that perform "if not exists then insert", how can I ensure that only one thread inserts a document in DB.</p>
  
  <p>What I tried is:</p>
  
  <pre><code> void test(DBContext context)
      {
  
          var person = new Person() { Id = Guid.NewGuid(), Name = "name", Title = "title", ReceivedAt = DateTime.Now };
          Console.WriteLine(DateTime.Now);
          var update = Builders&lt;Person&gt;.Update.Combine(
                Builders&lt;Person&gt;.Update.SetOnInsert(y =&gt; y.Name, person.Name)
              , Builders&lt;Person&gt;.Update.SetOnInsert(y =&gt; y.Title, person.Title)
              , Builders&lt;Person&gt;.Update.SetOnInsert(y =&gt; y.ReceivedAt, person.ReceivedAt)
              , Builders&lt;Person&gt;.Update.SetOnInsert(y =&gt; y.Id, person.Id));
          var result = context.People.FindOneAndUpdateAsync&lt;Person&gt;(
              x =&gt; x.Title == person.Title &amp;&amp; x.Name == person.Name &amp;&amp; x.ReceivedAt &gt; person.ReceivedAt - TimeSpan.FromSeconds(10),
              update,
              new FindOneAndUpdateOptions&lt;Person&gt;() { IsUpsert = true,ReturnDocument = ReturnDocument.Before}).GetAwaiter().GetResult();
          if (result?.Id != null)
          {
              Console.WriteLine("duplicate");
          }
          else
          {
              Console.WriteLine("first time");
          }
      }
  </code></pre>
  
  <p>And tested it using:</p>
  
  <pre><code>DBContext context = new DBContext ();
  for (int i = 0; i &lt; 10; i++)
    {
     Task.Run(() =&gt; test(context));
    }
  </code></pre>
  
  <p>But the above code inserts more than one document to collection, seems like <code>FindOneAndUpdateAsync</code> is not atomic. </p>
  
  <p>Is there a way to achieve that only one thread inserts a document into collection in Mongodb?</p>