How to get the key from the value in firebase

If anyone needs to do this using Kotlin:

mDatabase.child("clubs")
        .orderByChild("name")
        .equalTo("efg")
        .addListenerForSingleValueEvent(object: ValueEventListener {

            override fun onDataChange(dataSnapshot: DataSnapshot) {

                dataSnapshot.children.forEach {
                     //"it" is the snapshot
                     val key: String = it.key.toString()
                }
            }

            override fun onCancelled(p0: DatabaseError) {
                    //do whatever you need
            }
         })

That's because you're using a ValueEventListener. If the query matches multiple children, it returns a list of all those children. Even if there's only a single matches child, it's still a list of one. And since you're calling getKey() on that list, you get the key of the location where you ran the query.

To get the key of the matches children, loop over the children of the snapshot:

mDatabase.child("clubs")
         .orderByChild("name")
         .equalTo("efg")
         .addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for (DataSnapshot childSnapshot: dataSnapshot.getChildren()) {
            String clubkey = childSnapshot.getKey();

But note that if you assume that the club name is unique, you might as well store the clubs under their name and access the correct one without a query:

mDatabase.child("clubs")
         .child("efg")
         .addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        String clubkey = dataSnapshot.getKey(); // will be efg