0
votes

My idea is to create a like&unlike system for posts (a user can like and unlike a post) and to show a list of users in a fragment, ordered this way: the top user is the one for which there are the most numerous likes.

In my Firebase Firestore database:

  • I have a collection of posts. Each document (which is a post) contains the ID of the user that created it, and a counter of likes (I call it "A").

  • I have another collection, of users. Each document (which is a user) contains a counter (I call it "B") that counts for the number of likes, all posts combined.

For the moment, I use "B" to order the users in the list of users I've described above. I use "B" this way: return FirebaseFirestore.getInstance().collection("users").orderBy("likes", Query.Direction.DESCENDING);.

However, due to some technical facts in relation to Firebase Security Rules, and to simplify the database structure, I would want to only use "A", and remove "B". More precisely, I would want to get all the users, and order them according to "A". However, the counter "A" is defined in the documents of the collection of posts, whereas the counter "B" was defined in the documents of the collection of users: that makes it easier to use.

So my question is: for each user, I would have to get all their posts, then sum up their counter "A", then get all the users, then order them according to this sum. However, I would want to know: is it possible to do this using Firebase Firestore Android API? (something like the instruction given before) In others words: How to order documents from a collection, according to the field of documents of another collection? But note that in fact it's more difficult, since I must sum up the counter "A" of each post created by the user.

1

1 Answers

2
votes

What you're trying to do is essentially a "join" type operation, which is not supported by Firestore. A Firestore query can only consider documents in a single collection at a time. If you have data from two collections to use for the purpose of generating query results, you will have at least two queries to perform.

The only real alternative you have is to introduce a third collection with data already merged from the other two collections that supports the query you want to make. This is common in NoSQL type databases, and is called "denormalization".