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, long incrementValue = 1);
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.
- Either pass
- Execute
CountersFor.Increment
- Execute
session.SaveChanges
for the changes to take effect
-
Note:
- Modifying a Counter using
Increment
only takes effect whensession.SaveChanges()
is executed. - To decrease a Counter's value, pass the method a negative number to
Increment
.
- Modifying a Counter using
Code Sample
// 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();
}