FirebaseFirestore 의 collectionGroup 에 대해서

반응형

Firestore's collectionGroup method allows you to query across all collections with the same name, regardless of their parent collection. This is particularly useful when you have a hierarchical data structure with nested collections and you want to perform a query that spans multiple collections at the same level in the hierarchy.

For example, consider a Firestore structure where you have a users collection, each user document contains groups sub-collection, and each group document contains a todos sub-collection:

users
  ├── user1
  │    ├── groups
  │    │    ├── group1
  │    │    │    ├── todos
  │    │    │    │    ├── todo1
  │    │    │    │    └── todo2
  │    │    └── group2
  │    │         └── todos
  │    │              ├── todo3
  │    │              └── todo4
  ├── user2
  │    └── ...
  └── ...

If you want to query all todos across all groups for all users, you can use collectionGroup('todos'):

CollectionReference todosCollection =
    FirebaseFirestore.instance.collectionGroup('todos');

This will return a Query object that represents the combined result of all todos collections across all groups sub-collections under all users. You can then perform queries, such as filtering, ordering, or limiting, on this Query object to retrieve the desired data.

QuerySnapshot todosSnapshot = await todosCollection.get();

In summary, collectionGroup allows you to perform queries that span multiple collections with the same name, regardless of their parent collections. This can be particularly useful for querying related data in a hierarchical Firestore structure.

반응형