简体   繁体   中英

Firestore query with subcollection reference from parent document

My Firestore database structure looks like this (as shown in image) 在此处输入图像描述

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). Edited: I have other's fields too along with country field, so I don't want to duplicate fields in posts sub-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)

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:

PS Please also don't forget to create an index .

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.

Duplicating a single field "country" should do it as Alex mentioned in his answer. If you need to query based on multiple fields in user's doc then first method can work too

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM