Skip to content

Commit 329f576

Browse files
authored
Add fs_update_document_increment snippet (GoogleCloudPlatform#1547)
1 parent c621a69 commit 329f576

2 files changed

Lines changed: 27 additions & 0 deletions

File tree

firestore/src/main/java/com/example/firestore/snippets/ManageDataSnippets.java

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@
3535
import java.util.HashMap;
3636
import java.util.List;
3737
import java.util.Map;
38+
import java.util.concurrent.ExecutionException;
3839

3940
/** Snippets to demonstrate Firestore add, update and delete operations. */
4041
class 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
}

firestore/src/test/java/com/example/firestore/snippets/ManageDataSnippetsIT.java

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff 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);

0 commit comments

Comments
 (0)