Home > Net >  Firestore query with subcollection reference from parent document
Firestore query with subcollection reference from parent document

Time:04-11

My Firestore database structure looks like this (as shown in image)enter image description here

I have a users collection which has a posts sub-collection.

I want to fetch(query)all the posts by country(field of parent collection).

Is there any solution without any duplication of fields.

My code is below:

 val query: Query =
            postsRef
                .whereEqualTo("country", "USA"). // field from parent document
                .orderBy("createdAt", Query.Direction.DESCENDING)
                .limit(20)

CodePudding user response:

There is no way you can filter documents in a sub-collection based on the field that exists in the parent document. The best option that you have is to add the country field inside each post and use a collection group query like this:

val query = db.collectionGroup("posts")
                .whereEqualTo("country", "USA")
                .orderBy("createdAt", Query.Direction.DESCENDING)
                .limit(20)

In this way, you'll be able to get only the post from the USA. If you however need to query collections in Firestore under a certain path, please check the following article:

P.S. Please also don't forget to create an index.

CodePudding user response:

You'll have to first query users in that country and then fetch their posts or alternatively store the country in post document as you've mentioned in your question.

  • Related