首页 > 解决方案 > 特定路径内的collectionGroup

问题描述

我想做一个集合组查询,但在某个路径内,这意味着我不仅想用 collectionId 来定位集合,还想用集合所在的位置来定位集合。

让我们使用文档中使用的示例来更好地解释它。我们将在城市中拥有地标,在他们自己的收藏中拥有“一般”地标:

let citiesRef = db.collection('cities');

let landmarks = Promise.all([
  citiesRef.doc('SF').collection('landmarks').doc().set({
    name: 'Golden Gate Bridge',
    type: 'bridge'
  }),
  citiesRef.doc('SF').collection('landmarks').doc().set({
    name: 'Legion of Honor',
    type: 'museum'
  }),
  citiesRef.doc('LA').collection('landmarks').doc().set({
    name: 'Griffith Park',
    type: 'park'
  }),
  citiesRef.doc('LA').collection('landmarks').doc().set({
    name: 'The Getty',
    type: 'museum'
  }),
  citiesRef.doc('DC').collection('landmarks').doc().set({
    name: 'Lincoln Memorial',
    type: 'memorial'
  })
]);

let generalLandmarks = Promise.all([
  db.collection('landmarks').doc().set({
    name: 'National Air and Space Museum',
    type: 'museum'
  }),
  db.collection('landmarks').doc().set({
    name: 'Ueno Park',
    type: 'park'
  }),
  db.collection('landmarks').doc().set({
    name: 'National Museum of Nature and Science',
    type: 'museum'
  }),
  db.collection('landmarks').doc().set({
    name: 'Jingshan Park',
    type: 'park'
  }),
  db.collection('landmarks').doc().set({ 
    name: 'Beijing Ancient Observatory',
    type: 'museum'
  })
]);

现在我想查询城市中的地标而不是一般地标。以更简单的方式,我想做这样的事情:

let museums = db.collection('cities').collectionGroup('landmarks').where('type', '==', 'museum');

可能吗 ?

标签: firebasegoogle-cloud-firestore

解决方案


Cloud Firestore 目前无法做到这一点。当您执行集合组查询时,它将使用具有给定名称的所有集合和子集合。您无法将查询范围缩小到特定集合。

您可以做的是在每个子集合的文档中存储一个字段,以标识它们属于哪个顶级集合,然后使用该字段过滤您的结果。


推荐阅读