Reputation: 1697
I have TextView and I want to show player rank like Your Rank Is 6th
There is a collection that has 8 documents, Inside every document has field named player_name and player_score
.
player_name
= Liam , player_score
= 14player_name
= Noah , player_score
= 72player_name
= Oliver , player_score
= 18player_name
= Elijah , player_score
= 139player_name
= William , player_score
= 419player_name
= James , player_score
= 832player_name
= Benjamin , player_score
= 1932player_name
= Lucas , player_score
= 6Let us suppose I signed in by James account, So the TextView should show me this result after using OrderBy Descending
on Firestore -> Your Rank Is 2nd
How can I do it?
Note 1 : Is that will cost me 1800 reads in my quota because in fact I have more than 1800 documents not 8?
Note 2 : Every document name is player id
Upvotes: 0
Views: 152
Reputation: 50850
You can query the leaderboard like this:
CollectionReference citiesRef = db.collection("players");
citiesRef.orderBy("player_score").limit(10);
As you can see I have set the limit of documents to retrieve to 10 (i.e. top 10 users with highest scores) so I'll be charged 10 reads only. You get charged for amount of documents you are retrieving/reading. Firestore automatically indexes single fields so the queries are fast. You can get a detailed explanation here.
Do note that if you don't have that .limit()
set then Firestore will pull all the documents in that collection and costing you that many reads.
Coming to the part where you need to show the user's rank, that cannot be done by the query I mentioned above instead you'll have to paginate the query as mentioned here. Although that may incur additional reads.
Upvotes: 1