Skip to content
Advertisement

How can I delete a document in Firebase after sorting by a specific field?

I am currently working with Android Studio (with Java) and am having some trouble deleting a document. Say I am using a “Collection” with a “document” with a specific “field”. I need to delete the document if the field is “apple” but I don’t know the actual document name.

Currently the code that I am using (by looking at other answers) is:

db
.collection("Collection")
.whereEqualTo("field", "apple")
.addSnapshotListener(new EventListener<QuerySnapshot>() {
    @Override
    public void onEvent(@Nullable QuerySnapshot value, @Nullable FirebaseFirestoreException error) {
        value.delete();
    }
});

I was wondering how to delete the entire “document” based on just knowing if the field is “apple”. Thank you!

Advertisement

Answer

You can get list of documents from the query snapshot, then loop through the list and delete the documents. Using the given example:

db.collection("Collection")
                .whereEqualTo("field", "apple")
                .addSnapshotListener(new EventListener<QuerySnapshot>() {
                    @Override
                    public void onEvent(@Nullable QuerySnapshot value, @Nullable FirebaseFirestoreException error) {
                        if (value != null && !value.getDocuments().isEmpty()) {
                            List<DocumentSnapshot> documents = value.getDocuments();
                            for (DocumentSnapshot document : documents) {
                                DocumentReference documentReference = document.getReference();
                                documentReference.delete();
                            }
                        }
                    }
                });

When not requiring realtime updates you can use:

db.collection("Collection")
                .whereEqualTo("field", "apple")
                .get()
                .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
                    @Override
                    public void onComplete(@NonNull Task<QuerySnapshot> task) {
                        List<DocumentSnapshot> documents = task.getResult().getDocuments();
                        for (DocumentSnapshot document : documents) {
                            DocumentReference documentReference = document.getReference();
                            documentReference.delete();
                        }
                    }
                });
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement