Skip to main content

Create or Modify Counters

  • Use the CountersFor.Increment method to create a new Counter or modify an existing Counter's value.

  • If the Counter exists, Increment will add the specified number to the Counter's current value.
    If the Counter doesn't exist, Increment will create it and set its initial value.

  • For all other CountersFor methods see this Overview.

  • In this page:

Increment usage

Flow:

  • Open a session.
  • Create an instance of CountersFor.
  • Call CountersFor.Increment.
  • Call session.SaveChanges for the changes to take effect.

Note:

  • Modifying a Counter using Increment only takes effect when session.SaveChanges() is executed.
  • To decrease a Counter's value, pass the method a negative number to the Increment method.

Example

// 1. Open a session
using (var session = docStore.OpenSession())
{
// 2. pass CountersFor's constructor a document ID
var documentCounters = session.CountersFor("products/1-C");

// 3. Use `CountersFor.Increment`
documentCounters.Increment("ProductLikes"); // Increase "ProductLikes" by 1, or create it with a value of 1
documentCounters.Increment("ProductDislikes", 1); // Increase "ProductDislikes" by 1, or create it with a value of 1
documentCounters.Increment("ProductPageViews", 15); // Increase "ProductPageViews" by 15, or create it with a value of 15
documentCounters.Increment("DaysLeftForSale", -10); // Decrease "DaysLeftForSale" by 10, or create it with a value of -10

// 4. Save changes to the session
session.SaveChanges();
}

Syntax

void Increment(string counterName, long incrementValue = 1);
ParameterTypeDescription
counterNamestringCounter's name
deltalongIncrease Counter by this value.
Default value is 1.
For a new Counter, this number will be its initial value.