Skip to content Skip to sidebar Skip to footer

How To Add/update/remove Array Elements In Firebase Firestore Android Using Hashmap? A Store Database

I want to make a collection of users, users will have multiple stores as documents, each document have fields like storeName, storeAddress and availableProducts. My question is tha

Solution 1:

Good news guys, with the latest improvement to arrays you can add, update and remove an array element.

Check out this blog post: Better Arrays in Cloud Firestore!

You can do it like this

//Map to add user to array
final Map<String, Object> addUserToArrayMap = newHashMap<>();
addUserToArrayMap.put("arrayOfUsers", FieldValue.arrayUnion(mAuth.getCurrentUser().getUid()));

//Map to remove user from array
final Map<String, Object> removeUserFromArrayMap = newHashMap<>();
removeUserFromArrayMap.put("arrayOfUsers", FieldValue.arrayRemove(mAuth.getCurrentUser().getUid()));

//use either maps to add or remove user
db.collection("REFERENCE").document("mDocumentId")
                .update(addUserToArrayMap);

Solution 2:

Edit: September 12, 2018

Starting with August 28, 2018, now it's possible to update array members. More informations here.


How to Add/Update/Remove array elements in firebase firestore?

The short answer is that you cannot! As in the official documentation regarding arrays:

Although Cloud Firestore can store arrays, it does not support querying array members or updating single array elements.

So there is currently no way to add, update or remove a single array element in a Cloud Firestore database.

Seeing your database schema I can say that you don't have any arrays. The availableProducts is an object, beneath it there is a map named 0 which holds two String properties, spName and spPrice. If you want to update, let's say the price, please use the following code:

FirebaseFirestore rootRef = FirebaseFirestore.getInstance();
DocumentReference ref = rootRef.collection("gdgsghs.cok").document("Shsheg");
Map<String, Object> availableProducts = newHashMap<>();
Map<String, Object> zeroMap = newHashMap<>();
Map<String, Object> product = newHashMap<>();
product.put("spPrice", 63.121);
zeroMap.put("0", product);
availableProducts.put("availableProducts", zeroMap);
ref.set(availableProducts, SetOptions.merge());

Your price will be updated from 67.368 to 63.121.

Solution 3:

This is how you can add a new item to an existing collection inside a document :

FirebaseFirestore.getInstance().collection("COLLECTION_NAME").document("DOCUMENT_ID").update("NAME_OF_COLLECTION_NODE",FieldValue.arrayUnion(NEW_VALUE_OF_ANY_TYPE))

check this link for more info: https://firebase.googleblog.com/2018/08/better-arrays-in-cloud-firestore.html

Post a Comment for "How To Add/update/remove Array Elements In Firebase Firestore Android Using Hashmap? A Store Database"