Skip to content
Advertisement

Checking if a document exists in a Firestore collection

I have a Firestore collection tree in which I plan to store only one document. I want to check if that collection contains that document and if so, retrieve the id of the document! Any ideas/thoughts?

Thanks 🙂

Advertisement

Answer

If you want to check a particular document for existence based on its document id, please use the following lines of code:

FirebaseFirestore rootRef = FirebaseFirestore.getInstance();
DocumentReference docIdRef = rootRef.collection("yourCollection").document(docId);
docIdRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
    @Override
    public void onComplete(@NonNull Task<DocumentSnapshot> task) {
        if (task.isSuccessful()) {
            DocumentSnapshot document = task.getResult();
            if (document.exists()) {
                Log.d(TAG, "Document exists!");
            } else {
                Log.d(TAG, "Document does not exist!");
            }
        } else {
            Log.d(TAG, "Failed with: ", task.getException());
        }
    }
});

If you don’t have the document id, you need to use a query and find that document according to a value of a specific property like this:

FirebaseFirestore rootRef = FirebaseFirestore.getInstance();
CollectionReference yourCollRef = rootRef.collection("yourCollection");
Query query = yourCollRef.whereEqualTo("yourPropery", "yourValue");
query.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
    @Override
    public void onComplete(@NonNull Task<QuerySnapshot> task) {
        if (task.isSuccessful()) {
            for (QueryDocumentSnapshot document : task.getResult()) {
                Log.d(TAG, document.getId() + " => " + document.getData());
            }
        } else {
            Log.d(TAG, "Error getting documents: ", task.getException());
        }
    }
});
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement