I have two Activities, I am adding data to Firestore from these two activities individually. But, whenever I add second activity data to Firestore, it is overwriting the first activity data. I used below code in the two activities:
firebaseFirestore.collection("Users").document(user_id).set(data)
How to stop overwriting? I want to save both Activities data in the same user_id
.
Firestore now has a specific operator for this called FieldValue. increment() . By applying this operator to a field, the value of that field can be incremented (or decremented) as a single operation on the server.
Yes, this is possible using a combination of two collections, Firestore rules and batched writes. The simple idea is, using a batched write, you write your document to your "data" collection and at the same write to a separate "index" collection where you index the value of the field that you want to be unique.
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.
If you know that the user document allready exists in firestore then you should use
firebaseFirestore.collection("Users").document(user_id).update(data)
If you don't know if the document exists then you can use
firebaseFirestore.collection("Users").document(user_id).set(data, {merge:true})
This performs a deep merge of the data
Alternatively you can do it by using subcollections
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With