Firebase database sort by deeper child

后端 未结 2 1724
离开以前
离开以前 2021-01-25 19:49

Considering the following structure of the Firebase database:

  • root
    • game1
      • $playerUidA
        • score: 50
      • $playerUidB
2条回答
  •  走了就别回头了
    2021-01-25 20:02

    Although this question is rather old there might be people (like me) stumbling over it. Especially because it is pretty intuitive to structure the database in a similar way the author of the question did, to create (for example) a leaderboard system for a game. Since the answer is a bit outdated I wanted to add some things.

    Some time ago the devs added the possibility to order by deeply nested children! (See Ordering by a specified child key) To do so you basically have to do the exact same thing the author did and additionally use the first part of the answer given by @adolfosrs. Basically you have to do two things:

    1. Work with .indexOn (as described by @adolfosrs)
    2. Use the OrderByChild() command.

    To make this work on the example given by @steliosf you would have to do the following:

    First set the .indexOn in your database rules:

    {
      "rules": {
        "$gameId": {
          ".indexOn": "score",
          "$playerUid": {
            ...  
          }
        }
      }
    }
    

    Second use the Command the author of the question already used:

    rootRef.Child("root").OrderByChild("score")
    

    I would recommend that you always add a LimitToFirst() or LimitToLast() command to avoid that you pull the whole database which might be a lot of data (depending on the size of your database of course). To get for example the top 10 scores you could use:

    rootRef.Child("root").OrderByChild("score").LimitToLast(10)
    

    Since the data is ordered in ascending order you need to use LimitToLast().

提交回复
热议问题