简体   繁体   中英

Firebase: Query ordered by children count

In my firebase database, I have a child called Hashtag. That child contains names of hashtags, and that child contains the posts that are apart of those hashtags.

For example

Hashtags
    L #firstHashtag
            L post1: true
            L post2: true
            L post3: true
    L #secondHashtag
            L post4: true
            L post5: true
            L post6: true
            L post7: true
            L post8: true
    L #thirdHashtag
            L post9: true

That is how my database looks.

First hashtag has three posts.

Second hashtag has five posts.

Third hashtag has one post.

This is my hashtag reference

var HASHTAG_REFERENCE = Database.database().reference().child("Hashtags")

My goal is to query the hashtags in order of most popular. A hashtag with the most posts is the most popular hashtag. A hashtag with the least posts is the least popular hashtag.

So the most popular hashtag would be secondHashtag, and I want to receive the name of that hashtag first. The least popular hashtag is thirdHashtag, and i want to receive the name of that hashtag last

How can i query my database so it can order the children in terms of their post count?

There's no native query that lets you order by number of children. Instead, you'll have to maintain a count of the posts, stored in another child, and order the hashtags by the value of that.

You have two choices for this. You can maintain the count on the client whenever it adds a post to a hashtag. Or, write a Cloud Function that automatically keeps the count up to date whenever something changes. In either case, be sure to use a transaction to avoid conflict from multiple writers.

Also bear in mind that, because you want the reverse order of the count of posts, you'll have to store a value that naturally orders from most posts to least posts. You could store a negative count to make sure the most popular posts (which therefore have the smallest values) are ordered ahead of the least popular (which have the largest values).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM