Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firestore perform delete based on condition

Is there a way I can perform a delete on Firestore documents where field1 =x and field2 = y?

I see the delete function but does not come with where. If I use the transaction then there is get and delete but the get does not seem to accept "where" clause.

I hope I am missing something in the documentation.

Thanks

like image 705
Snake Avatar asked Mar 07 '18 05:03

Snake


1 Answers

To achieve this, you need to create the desired query first and then just use the delete() method like this:

FirebaseFirestore rootRef = FirebaseFirestore.getInstance();
CollectionReference itemsRef = rootRef.collection("yourCollection");
Query query = itemsRef.whereEqualTo("field1", "x").whereEqualTo("field2", "y");
query.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
    @Override
    public void onComplete(@NonNull Task<QuerySnapshot> task) {
        if (task.isSuccessful()) {
            for (DocumentSnapshot document : task.getResult()) {
                itemsRef.document(document.getId()).delete();
            }
        } else {
            Log.d(TAG, "Error getting documents: ", task.getException());
        }
    }
});
like image 72
Alex Mamo Avatar answered Sep 17 '22 05:09

Alex Mamo