Max
Max

Reputation: 788

Cloud Firestore: does updating the same document twice in a batch count as a single write?

I want to update one field and, in some case, another field of the same document in a batch:

db.runBatch { batch ->
    val myRef = db.document("path/to/document")
    batch.update(myRef, "foo", "bar")

    if(someCondition) {
        batch.update(myRef, "baz", "bar")
    }
}

Is this billed as a single write or as two writes in case someCondition is true?

As an alternative I could do something like this:

db.runBatch { batch ->
    val myRef = db.document("path/to/document")

    if(someCondition) {
        batch.update(myRef, "foo", "bar", "baz", "bar")
    } else {
        batch.update(myRef, "foo", "bar")
    }
}

But that leads to duplicating code and becomes very messy in case of updating more fields

Upvotes: 4

Views: 1326

Answers (1)

Doug Stevenson
Doug Stevenson

Reputation: 317362

It should be only one write, but this is very easy to work around if you don't have confidence in that. Just take a different approach where you build the Map of updates just once, and pass the to update() which takes a Map:

db.runBatch { batch ->
    val myRef = db.document("path/to/document")
    val obj = if (someCondition) {
        mapOf("foo" to "bar", "baz" to "bar")
    }
    else {
        mapOf("foo" to "bar")
    }

    batch.update(myRef, obj)
}

Upvotes: 3

Related Questions