How to add values to Firebase Firestore without overwriting?
There are two ways in which you can achieve this. First one would be to use a Map
:
Map<String, Object> map = new HashMap<>();
map.put("yourProperty", "yourValue");
firebaseFirestore.collection("Users").document(user_id).update(map);
As you can see, I have used update()
method instead of set()
method.
The second approach would be to use an object of your model class like this:
YourModelClass yourModelClass = new YourModelClass();
yourModelClass.setProperty("yourValue");
firebaseFirestore.collection("Users").document(user_id)
.set(yourModelClass, SetOptions.mergeFields("yourProperty"));
As you can see, I have used the set()
method but I have passed as the second argument SetOptions.mergeFields("yourProperty")
, which means that we do an update only on a specific field.
I suggest you to add one more document or collection that it will be able to store more just one data values for single user.
You can create a document references for both activities:
firebaseFirestore.collection("Users").document(user_id+"/acitivity1").set(data);
//and
firebaseFirestore.collection("Users").document(user_id+"/acitivity2").set(data);
Or you can create a sub-collection for it:
firebaseFirestore.collection("Users").document(user_id)
.collection("Activities").document("acitivity1").set(data);
//and
firebaseFirestore.collection("Users").document(user_id)
.collection("Activities").document("acitivity2").set(data);
More about hierarchical data there.