Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 525
Max Avatar asked Oct 20 '25 02:10

Max


1 Answers

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)
}
like image 143
Doug Stevenson Avatar answered Oct 21 '25 15:10

Doug Stevenson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!