Reputation: 3128
I'm using Firebase Cloud database. I queried a collection and got a list of documents. Each document contains a field cars
which contains strings. In case the array contains at least three strings I want to remove the string carPath
from this array (not the whole array). Otherwise, it should remove the whole document. I'm using WriteBatch. What I did:
fireDB.document(groupPath).collection("users").whereArrayContains("cars",carPath).get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
@Override
public void onComplete(@NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful() && task.getResult() != null) {
QuerySnapshot snapshot = task.getResult();
for (DocumentSnapshot curr : snapshot.getDocuments()) {
List<String> cars = (List<String>) curr.get("cars");
if (cars == null) continue;
if (cars.size() <= 2) {
batch.delete(snapshot.getReference());
} else {
// What to do here?
}
}
}
}
});
How should I remove one item in the list with WriteBatch?
Upvotes: 0
Views: 30
Reputation: 317467
What you're trying to do is just a document update. You can do a regular update with FieldValue.arrayRemove(). Except you will do it in the context of a batch using update() instead of a standalone update.
batch.update(snapshot.getReference(), "cars", FieldValue.arrayRemove(carPath));
Upvotes: 1