3

I have this Firebase Cloud Firestore schema:

my_db -> users -> uid -> places -> placeId

and

my_db -> places -> placeId

Will this collection group queries get places within both path? If yes, for sure I get duplicates. Is there any way I can avoid that?

Edit: My goal is to get all places within all users and not all places within all collections in my database.

Sky Tracker
  • 143
  • 1
  • 8
  • The answer is yes, a collection group queries on the `places` collection will return documents from all the collections named `places`, whether they are sub-collections, sub-sub-collections, etc., or root collections. I don't know however if there is a way to avoid this behavior. – Renaud Tarnec May 20 '19 at 13:26
  • @RenaudTarnec Thanks for your comment. If you find a way to avoid this, please add it as an answer. I really need it. – Sky Tracker May 20 '19 at 13:49
  • Actually I don't know how to avoid it, this is why I wrote a comment and not an answer :-) – Renaud Tarnec May 20 '19 at 14:00
  • @RenaudTarnec Thanks anyway. – Sky Tracker May 20 '19 at 14:09
  • A collection group is a group of collections with the same ID. So in your case you would have set up a collection group with the ID 'places'. One purpose is to be able to query across that group. If you don't want to do that, why set up a collection group in the first place? Also, you may just want to consider keeping places in either users or places but not both. – Jay May 20 '19 at 20:31

1 Answers1

6

Collection group queries always look at all top-level collections and subcollections with any path at any depth with the name you provide. There is no way to change this behavior. You will need to name your collections differently if you want to limit the scope of the query.

If you can't change your database structure, you could at least ignore the results from the collections you're not interested in by filtering the documents on the client by looking at the path of the document in the snapshots you receive, and deciding for yourself if you should process that document.

Another strategy would be to put a boolean field in the documents of each one of your subcollections that does not exist in the top-level collection documents. You can use this field to query only for only the documents in the subcollections.

Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
  • 1
    Unfortunately, I cannot change the database structure, so the last solution is the one that worked for me. So I have added a new property on each document in the `places` subcollection and added a extra where call to the query. Works perfect now. Thank you Stevenson. – Sky Tracker May 20 '19 at 18:42