4
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Firestore】collectionGroup の where で先祖ドキュメント(親ドキュメントなど)を指定する方法

Last updated at Posted at 2022-02-02

以下のコードで a/bドキュメント以下のcollectionGroupだけを取得できるみたいです。
a/b/c/d/${collectionGroup}なども取得されるみたいです。)

firestore
  .collectionGroup(collectionGroup)
  .where(FieldPath.documentId(), '>=', `a/b`)
  .where(FieldPath.documentId(), '<=', 'a/b0')
  .get();

調べた経緯

この動画の 37:20 あたりの質問への回答として上記の方法が話されていました。

上記の方法を使ったコードがどこかに書いてあった、と話されていたので、調べた所、以下が見つかりました。

このコメントのリンク先が以下です。

リンク先の関連部分のコードを抜粋します:

const docPaths = [
  `a/a/${collectionGroup}/cg-doc1`,
  `a/b/a/b/${collectionGroup}/cg-doc2`,
  `a/b/${collectionGroup}/cg-doc3`,
  `a/b/c/d/${collectionGroup}/cg-doc4`,
  `a/c/${collectionGroup}/cg-doc5`,
  `${collectionGroup}/cg-doc6`,
  `a/b/nope/nope`,
];

// ...

let querySnapshot = await firestore
  .collectionGroup(collectionGroup)
  .where(FieldPath.documentId(), '>=', `a/b`)
  .where(FieldPath.documentId(), '<=', 'a/b0')
  .get();
expect(querySnapshot.docs.map(d => d.id)).to.deep.equal([
  'cg-doc2',
  'cg-doc3',
  'cg-doc4',
]);

余談:「collectionGroup 親ドキュメント 指定」でググったときに出て欲しかったので、タイトルに「親ドキュメント」って入れました。

4
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?