简体   繁体   中英

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!

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();
                        }
                    }
                });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM