Home > database >  Firebase orderBy query
Firebase orderBy query

Time:07-01

I want to fetch polls whose pollEndingTime is greater than the current time so for that reason I have used where query and in order to work where query I have applied orderBy on pollEndingTime also, but also I have to orderBy it in terms of totalVote received till now. So my query is looking like this:


 query = FirebaseFirestore.instance
          .collection("polls")
          .where("pollEndingTime", isGreaterThanOrEqualTo: Timestamp.now())
          .orderBy("pollEndingTime", descending: true)
          .orderBy("totalVote", descending: true);

Here there is no effect of orderBy on totalVote. So how can I achieve my goal to fetch polls based on totalVote in descending form and also their pollEndingTime is greater than or equal to current timestamp?

CodePudding user response:

If you have multiple orderBy statements in a single query, the database handles them in the order specified. So the results you get are first ordered by pollEndingTime and only then on totalVote. The consequence of this is that the ordering of totalVote is only visible for results that have the exact same pollEndingTime, which apparently wasn't the case in the data set that you tested with.

There is no alternative for this in the API, as it would require the server to reorder the data which it can't do at scale without violating its performance guarantees. So you will have to reorder the results in your application code after retrieving them, for example by calling sort.

  • Related