File tree Expand file tree Collapse file tree
main/java/com/example/firestore/snippets
test/java/com/example/firestore/snippets Expand file tree Collapse file tree Original file line number Diff line number Diff line change 3535import java .util .HashMap ;
3636import java .util .List ;
3737import java .util .Map ;
38+ import java .util .concurrent .ExecutionException ;
3839
3940/** Snippets to demonstrate Firestore add, update and delete operations. */
4041class ManageDataSnippets {
@@ -426,4 +427,20 @@ void writeBatch() throws Exception {
426427 }
427428 // [END fs_write_batch]
428429 }
430+
431+ public void updateDocumentIncrement () throws ExecutionException , InterruptedException {
432+ final City city = new City ();
433+ city .setPopulation (100L );
434+ db .collection ("cities" ).document ("DC" ).set (city ).get ();
435+
436+ // [START fs_update_document_increment]
437+ DocumentReference washingtonRef = db .collection ("cities" ).document ("DC" );
438+
439+ // Atomically increment the population of the city by 50.
440+ final ApiFuture <WriteResult > updateFuture = washingtonRef
441+ .update ("population" , FieldValue .increment (50 ));
442+ // [END fs_update_document_increment]
443+ updateFuture .get ();
444+ }
445+
429446}
Original file line number Diff line number Diff line change @@ -188,6 +188,16 @@ public void testWriteBatchIsSuccessful() throws Exception {
188188 assertFalse (document .get ().exists ());
189189 }
190190
191+ @ Test
192+ public void testUpdateDocumentIncrementSuccessful () throws Exception {
193+ manageDataSnippets .updateDocumentIncrement ();
194+ CollectionReference collection = db .collection ("cities" );
195+ DocumentReference documentReference = collection .document ("DC" );
196+ final DocumentSnapshot data = documentReference .get ().get ();
197+ assertTrue (data .contains ("population" ));
198+ assertEquals ((Long ) 150L , data .getLong ("population" ));
199+ }
200+
191201 @ AfterClass
192202 public static void tearDown () throws Exception {
193203 manageDataSnippets .deleteCollection (db .collection ("cities" ), 10 );
You can’t perform that action at this time.
0 commit comments