Creating and Modifying 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 a number to the Counter's current value.
    If the Counter doesn't exist, increment will create it and set its initial value.

  • In this page:


increment Syntax

void increment(String counterName);
void increment(String counterName, long incrementValue);
Parameters Type Description
counterName String Counter's name
incrementValue Long Increase Counter by this value. Default value is 1.
For a new Counter, this will be its initial value.

increment Usage

  • Flow:

    • Open a session
    • Create an instance of countersFor.
      • Either pass countersFor an explicit document ID, -or-
      • Pass it an entity tracked by the session, e.g. a document object returned from session.query or from session.load.
    • Execute countersFor.increment
    • Execute 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 increment.

Code Sample

// 1. Open a session
try (IDocumentSession session = docStore.openSession()) {
    // 2. pass CountersFor's constructor a document ID
    ISessionDocumentCounters 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();
}