Firestore update only one field

AndroidFirebaseGoogle Cloud-Firestore

Android Problem Overview


I have a database. The sequence is: collections - document - hashmaps. For example:

users - the name of the collection

users.uid - the name of the document

Hashmap the document consists of a lot of hashmaps user data Hashmap Hashmap etc

Hashmap: the name of user is the key and telephone, location etc are the values. I need to update only one field(location) for one username, but can't understand how do this?

I tried the next way (update phone number for alex):

User user = new User();
user.setPhone(131902331);

Map<String,RealmObject> userMap = new HashMap<>();
userMap.put("alex",user);

          mFirebaseFirestore
                  .collection("users")
                  .document(mFirebaseAuth.getUid())
                  .set(userMap, SetOptions.merge())
                  .addOnSuccessListener(new OnSuccessListener<Void>() {
                      @Override
                      public void onSuccess(Void aVoid) {
                          LOG.info("Success");
                      }
                  })
                  .addOnFailureListener(new OnFailureListener() {
                      @Override
                      public void onFailure(@NonNull Exception e) {
                          LOG.error("Failure "+e.toString());
                      }
                  });

What I am doing wrong?

Android Solutions


Solution 1 - Android

I know it's almost a year old question, but this might help someone. Use dot notation

db.collection("users")
  .document("frank")
  .update({
    "age": 13,
    "favorites.color": "Red"
  });

Solution 2 - Android

When you call set() on a document, the existing contents of that documents are replaced with the data you pass in.

If you want to only update the values of the field you specify in a map, use update():

mFirebaseFirestore
  .collection("users")
  .document(mFirebaseAuth.getUid())
  .update(userMap)

See the Firestore documentation on updating a document.

Solution 3 - Android

Please note that as of 2021, the syntax in MrAleister's answer has changed a bit if using firebase-firestore-ktx (see documentation). I did not edit answer because perhaps it is still valid for people using other versions of the library.

// Assume the document contains:
// {
//   name: "Frank",
//   favorites: { food: "Pizza", color: "Blue", subject: "recess" }
//   age: 12
// }
//
// To update age and favorite color:
db.collection("users").document("frank")
        .update(mapOf(
                "age" to 13,
                "favorites.color" to "Red"
        ))

Solution 4 - Android

I'm finding some odd notation in some of these answers. Maybe firestore parameters were updated? At any rate, I wanted to post an answer of my own.

If you want to update a single element in your document, do so with the below code:

db.collection("users").document("frank")
  .update("age", 13);

The update() parameter accepts as many key/value pairs as you need, which are not separated by a colon, and are NOT put in some sort of array notation { } as shown in some of these answers. They are simply added in and separated by commas. See below:

.update( key , value , additionalkey, additionalvalue)

After update(), feel free to add your OnSuccess/OnFailure listeners as needed.

Solution 5 - Android

Dynamic nested reference:

def nest_update(new, parent):
    return {parent+'.'+new: val for new, val in list(new.items())}

Usage:

old = {'nested': {'a': 123,'b': 456, 'c': 789}}
new = {'b': 0}
    
print('\nOld:           ', old)
print('New:           ', nest_update(new, 'nested'))
print('New should be: ', {'nested.b': 0})


# OUTPUT
Old:            {'nested': {'a': 123, 'b': 456, 'c': 789}}
New:            {'nested.b': 0}
New should be:  {'nested.b': 0}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDelphianView Question on Stackoverflow
Solution 1 - AndroidMrAleisterView Answer on Stackoverflow
Solution 2 - AndroidFrank van PuffelenView Answer on Stackoverflow
Solution 3 - AndroidD2TheCView Answer on Stackoverflow
Solution 4 - AndroidFoxDonutView Answer on Stackoverflow
Solution 5 - AndroidRyan CocuzzoView Answer on Stackoverflow