Create or Modify Counters
-
Use the
CountersFor.Incrementmethod to create a new Counter or modify an existing Counter's value. -
If the Counter exists,
Incrementwill add the specified number to the Counter's current value.
If the Counter doesn't exist,Incrementwill create it and set its initial value. -
For all other
CountersFormethods see this Overview. -
In this page:
Increment usage
Flow:
- Open a session.
- Create an instance of
CountersFor.- Either pass
CountersForan 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.
- Either pass
- Call
CountersFor.Increment. - Call
session.SaveChangesfor the changes to take effect.
Note:
- Modifying a Counter using
Incrementonly takes effect whensession.SaveChanges()is executed. - To decrease a Counter's value, pass the method a negative number to the
Incrementmethod.
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);
| 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. |