Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to increment existing number field in Cloud Firestore

I have a field which indicates the number of transactions. I would like to increment it by 1 as soon as a transaction occurs. I could'nt find any method to directly execute this.

One method is to get the user first and then update the field with the received value + 1, but this is too lengthy and slow.

Can anyone tell me any other feasible method?

like image 576
Sangeeth Mukundan Avatar asked Jun 08 '18 14:06

Sangeeth Mukundan


People also ask

How do I update a field in firestore?

Firestore Update Document Field What if we want to just update a value of a specific field in an existing document. To do that, all we have to do is add a third argument to the setDoc() method. It will be a JavaScript object with a single property: merge:true.

How do I aggregate data in firestore?

If you want to gain insight into properties of the collection as a whole, you will need aggregation over a collection. Cloud Firestore does not support native aggregation queries. However, you can use client-side transactions or Cloud Functions to easily maintain aggregate information about your data.

How do you make a field unique in firestore?

The simple idea is, using a batched write, you write your document to your "data" collection and at the same write to a separate "index" collection where you index the value of the field that you want to be unique.


1 Answers

Firestore now has a specific operator for this called FieldValue.increment(). By applying this operator to a field, the value of that field can be incremented (or decremented) as a single operation on the server.

From the Firebase documentation on incrementing a numeric value:

var washingtonRef = db.collection('cities').doc('DC'); 
// Atomically increment the population of the city by 50. 
washingtonRef.update({     population: firebase.firestore.FieldValue.increment(50) }); 

So this example increments the population by 50, no matter what is current value is. If the field doesn't exist yet (or is not a number), it is set to 50 in this case.


If you want to decrement a number, pass a negative value to the increment function. For example: firebase.firestore.FieldValue.increment(-50)

like image 61
Frank van Puffelen Avatar answered Oct 07 '22 03:10

Frank van Puffelen