Mahmudul Hasan Shohag
Mahmudul Hasan Shohag

Reputation: 3131

Query function for distinct result in firestore

Is there any Query function to get the distinct result in firestore.

For example:

Query query = colRef.orderBy("title")
                        .startAt("R")
                        .limit(10);

This gives me all the documents with "title" starting with "R", which contain duplicates like this:

Recording
Running
Running
Running

How can I get a distinct result like this:

Recording
Running

Upvotes: 5

Views: 9162

Answers (1)

Alex Mamo
Alex Mamo

Reputation: 138824

Unfortunately there is no distinct() method within Cloud Firestore. Because you are ordering your data by title, which is a key within each child this is possible. To query your database and get only the distnict elements you need to come up with another solution which would be to create another node named distinctTitles in which you need to add all those titles. To avoid duplicate elements (overriding data), first you need to check for uniqueness using exists() method like this:

DocumentReference docRef = db.collection("distinctTitles").document("titleToCheck");
docRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
    @Override
    public void onComplete(@NonNull Task<DocumentSnapshot> task) {
        if (task.exists()) {
            //Do something
        } else {
            //Do something else
        }
    }
});

Upvotes: 6

Related Questions