title: How do you increment a field in mongodb using c#
body: <p>Thought this would be pretty straight forward, but my value is remaining the same (0).</p>
  
  <p>What I'd like to do is increment my UnreadMessages field when the user receives a message they haven't read and then decrement it when they have. So I thought code like this would work:</p>
  
  <pre><code>var userHelper = new MongoHelper&lt;User&gt;();
  //increment
  userHelper.Collection.Update(Query.EQ("Id", userId.ToId()), Update.Inc("UnreadMessages", 1));
  //decrement
  userHelper.Collection.Update(Query.EQ("Id", userId.ToId()), Update.Inc("UnreadMessages", -1));
  </code></pre>
  
  <p>After running these no errors are thrown but the value doesn't change either. And no I'm not running one after the other as the code above could be interpreted :)</p>
  
  <p><strong>Update</strong></p>
  
  <p>Here's my helper class:</p>
  
  <pre><code>public class MongoHelper&lt;T&gt; : Sandbox.Services.IMongoHelper&lt;T&gt; where T : class
  {
      public MongoCollection&lt;T&gt; Collection { get; private set; }
  
      public MongoHelper()
      {
          var con = new MongoConnectionStringBuilder(ConfigurationManager.ConnectionStrings["MongoDB"].ConnectionString);
          var server = MongoServer.Create(con);
          var db = server.GetDatabase(con.DatabaseName);
          Collection = db.GetCollection&lt;T&gt;(typeof(T).Name.ToLower());
      }
  }
  </code></pre>
  
  <p>and thanks to Travis' answer I was able to pull this off:</p>
  
  <pre><code>MongoHelper&lt;UserDocument&gt; userHelper = new MongoHelper&lt;UserDocument&gt;();
              var user = userHelper.Collection.FindAndModify(Query.EQ("Username", "a"), SortBy.Null, Update.Inc("MessageCount", 1), true).GetModifiedDocumentAs&lt;UserDocument&gt;();
  </code></pre>