LPFJ
LPFJ

Reputation: 195

How to use orderBy in Firestore?

Collections

I got two collections.

users and items.

Each document in items collection has uid, status and price.

What I'm Trying To Do

I want to rank users by how much price user has.

If in MySql, I could do it like this.

$users = User::leftJoin('items', 'users.uid', '=', 'items.uid')
    ->groupBy('users.id')
    ->where(items.status, 2)
    ->select('users.*', DB::raw('sum(items.price) as total_price'))
    ->orderBy('total_price', 'desc')
    ->limit(10)
    ->get();

I would appreciate it if you could tell me how to do it.

Thank you in advance.

Upvotes: 0

Views: 52

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 598887

Firestore (like many NoSQL databases) can't perform joins. Each query runs against a single collection, or against collection of the same name (with the same type of data in there).

If you want to sort users in the total price of their items, you'll have to store the total price of their items in each user's document, and update it whenever you write something to that user's items.

This is very common when dealing with NoSQL databases:

  1. You duplicate data to allow for a specific use-case.
  2. Your write operations become more complex, but they allow a use-case, and then allow that use-case to scale much better.

Upvotes: 1

Related Questions