Reputation: 1834
If I want to sort docs according to this scenario -
It might seem simple, just use this code -
DBRef.collection("col")
.where("count", isNotEqual: 0)
.orderBy("price")
.get();
But this will throw an error, due to the limitations of firebase firestore. So, we'll have to use another orderBy("count") query and also before any other orderBy query.
DBRef.collection("col")
.where("count", isNotEqual: 0)
.orderBy("count")
.orderBy("price")
.get();
And that'll sort the docs according to the count
field, and not according to the price field. How can I sort docs list according to the price
field at the same time.
I even tried a work around,
databaseReference
.collection("products")
.where("tags", arrayContains: tag)
.where("sellingPrice", isGreaterThan: 0)
.orderBy("sellingPrice", descending: isDesc)
.where("totalUnit", isGreaterThan: 0)
.orderBy("totalUnit")
.limit(limit)
.get()
I added another where statement for the "sellingPrice" field, so that I would have to add orderBy("sellingPrce") the first orderBy statement. But I'm still getting the error
Failed assertion: line 421 pos 16: 'field == orders[0][0]': The initial orderBy() field '[[FieldPath([sellingPrice]), false]][0][0]' has to be the same as the where() field parameter 'FieldPath([totalUnit])' when an inequality operator is invoked.
Upvotes: 0
Views: 1554
Reputation: 600131
The results of your second query will be sorted by count first, and then by price. There is no way to get them from the database without first sorting on count, so you will have to reorder them in your application code.
What you could consider is not giving the documents where the count is equal to 0
a count
field at all. This will result at them being excluded from the index, and that also means you can put the orderBy("count")
at the end of the query.
Alternatively, you can add a isInStock
type field that you update in sync with the count
field. Once you do that, you can do an equality condition (where("isInStock", "==", true)
), which doesn't require an orderBy
clause.
Upvotes: 1