Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 :)

like image 740
Emil Sharier Avatar asked Nov 16 '18 06:11

Emil Sharier


People also ask

How do I find out how many documents are in my firestore collection?

If you need a count, just use the collection path and prefix it with counters . As this approach uses a single database and document, it is limited to the Firestore constraint of 1 Update per Second for each counter.


1 Answers

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());
        }
    }
});
like image 97
Alex Mamo Avatar answered Oct 23 '22 01:10

Alex Mamo