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

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

    // Use `CountersFor.Increment`:
    // ============================
    
    // Increase "ProductLikes" by 1, or create it if doesn't exist with a value of 1
    documentCounters.Increment("ProductLikes"); 
    
    // Increase "ProductPageViews" by 15, or create it if doesn't exist with a value of 15
    documentCounters.Increment("ProductPageViews", 15);
    
    // Decrease "DaysLeftForSale" by 10, or create it if doesn't exist with a value of -10
    documentCounters.Increment("DaysLeftForSale", -10);

    // Execute all changes by calling SaveChanges
    session.SaveChanges();
}

Syntax

void Increment(string counterName, long delta = 1);
Parameter Type Description
counterName string Counter's name
delta long Increase Counter by this value.
Default value is 1.
For a new Counter, this number will be its initial value.