Reputation: 113
Here is my Firestore database structure:
Faculty (Collection)
--Document1
-memberId: "77777"
-fullName: "Vince Melmar Ybanez"
--Document2
-memberId: "12345"
-fullName: "John Doe"
--Document3
AnnualDue (Sub-Collection of Document1 in Faculty)
--Document1
-memberId: "77777"
-fullName: "Vince Melmar Ybanez"
--Document2
-memberId: "77777"
-fullName: "Vince Melmar Ybanez"
AnnualDue (Sub-Collection of Document2 in Faculty)
--Document3
-memberId: "12345"
-fullName: "John Doe"
AnnualDue (Collection)
--Document1
-memberId: "77777"
-fullName: "Vince Melmar Ybanez"
--Document2
-memberId: "77777"
-fullName: "Vince Melmar Ybanez"
--Document3
-memberId: "12345"
-fullName: "John Doe"
How to update the fullName
of member 1 (Document 1) from Vince Melmar Ybanez to Vince Ybanez in Faculty Collection, Annual Due Collection, and AnnualDue Sub-Collection?
Upvotes: 1
Views: 119
Reputation: 138824
If you're thinking of updating multiple documents that exist within multiple collections or subcollections in one go, please note that this is not possible. To solve this, you have to create three different operations.
Now to be able to update the "fullName" of "member 1" from "Vince Melmar Ybanez" to "Vince Ybanez" in the Faculty Collection, please use the following lines of code:
DocumentReference facultyDocOneRef = db.collection("Faculty").document("Document1");
Map<String, Object> update = new HashMap<>();
update.put("fullName", "Vince Ybanez");
facultyDocOneRef.update(update).addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if (task.isSuccessful()) {
Log.d(TAG, "Document updated successfully.");
} else {
Log.d(TAG, task.getException().getMessage()); //Never ignore potential errors!
}
}
});
Now to be able to update the remaining two fields within the other collections, you only need to create the references and use the exact same code as above:
DocumentReference annualDueDocOneRef = db.collection("AnnualDue").document("Document1");
annualDueDocOneRef.update(update).addOnCompleteListener(/*...*/);
And the last one:
DocumentReference facultyAnnualDueDocOneRef = db
.collection("Faculty").document("Document1")
.collection("AnnualDue").document("Document1");
facultyAnnualDueDocOneRef.update(update).addOnCompleteListener(/*...*/);
Upvotes: 1