0

We have a firestore collection, where each document has only one field names.

names contains a map.

Now if, I just want to update a single key value pair in that map, is there a way, other than:

 await FirebaseFirestore.instance
        .collection(namesCollectionName)
        .doc(docId)
        .update(savedNames.toJson())
        .whenComplete(() => {developer.log("Update saved names success")})
        .catchError((error) {
      developer.log("Update saved names failed: $error");
      throw Exception("Update saved names failed: $error");
    });

This code updates the entire map.

I am not sure if there is a way to update just a key value pair. I felt it would be more efficient!

Nithin Sai
  • 840
  • 1
  • 10
  • 23

2 Answers2

1

Firestore processes each entries in the map you pass as a set operation on that field.

If you want to update nested fields use . notation to mark that field. So say you store the full name for each user keyed on the Stack Overflow ID as a map under the names field, that'd be:

users
    .doc('ABC123')
    .update({'names.13076945': 'Nithin Sai'})

If your names field is an array and you want to add a certain name if it doesn't exist in there yet, that'd be an array-union, which looks like this:

users
    .doc('ABC123')
    .update({'names': FieldValue.arrayUnion(['Nithin Sai'])});
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • when ```updating nested fields```, I assume, if the key doesn't already exist, firestore auto creates a key and adds the value. But how does this work if I want to delete a key-val pair (without updating the entire map)? – Nithin Sai Oct 13 '21 at 19:07
  • 1
    You can use `FieldValue.delete()` for that. See https://stackoverflow.com/questions/48145962/firestore-delete-a-field-inside-an-object – Frank van Puffelen Oct 13 '21 at 19:30
0

consider the document was set in a form

{"bio":{"name":"frank", "age":20}}

then you can update age using the code below

# First of all set the reference to the document you want to update
ref = db.collection("users").document("frank")
ref.update({"bio.age":12})
ethry
  • 731
  • 6
  • 17