Home > database >  Firestore : Update only a key-val pair
Firestore : Update only a key-val pair

Time:10-15

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!

CodePudding user response:

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'])});
  • Related