Firestore query - checking if username already exists

Solution 1:

The following query returns all users with provided usernameToCheck. If username is unique then youll get only one documentSnapShot.

    Query mQuery = mFirebaseFirestore.collection("all_users")
                .whereEqualTo("username", "usernameToCheck");

      mQuery.addSnapshotListener(new EventListener<QuerySnapshot>() {
            @Override
            public void onEvent(QuerySnapshot documentSnapshots, FirebaseFirestoreException e) {

                for (DocumentSnapshot ds: documentSnapshots){
                    if (ds!=null){
               String userName = document.getString("username");
                        Log.d(TAG, "checkingIfusernameExist: FOUND A MATCH: " +userName );
                        Toast.makeText(getActivity(), "That username already exists.", Toast.LENGTH_SHORT).show();
                    }
                }
            }
        });

Solution 2:

To solve this, please use the following lines of code:

FirebaseFirestore rootRef = FirebaseFirestore.getInstance();
CollectionReference allUsersRef = rootRef.collection("all_users");
Query userNameQuery = allUsersRef.whereEqualTo("username", "userNameToCompare");
userNameQuery.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
    @Override
    public void onComplete(@NonNull Task<QuerySnapshot> task) {
        if (task.isSuccessful()) {
            for (DocumentSnapshot document : task.getResult()) {
                if (document.exists()) {
                    String userName = document.getString("username");
                    Log.d(TAG, "username already exists");
                } else {
                    Log.d(TAG, "username does not exists");
                }
            }
        } else {
            Log.d("TAG", "Error getting documents: ", task.getException());
        }
    }
});

In which userNameToCompare is of type String and is the user name of the user with which you want to make the comparison.