1

I want to get a snapshot of a Book by its document ID.

My structure looks like this:

           stores
          /      \
    Store1        Store2
      |               |
    books            books
    /   \           /  |  \
 Book1 Book2   Book3 Book4 Book5

(stores is a collection)

I tried with a collection group:

my_id = "XXXYYYZZZ" # I know that there is a book with this ID
firestore.Client.collection_group('books').where('id', "==", my_id)

But it looks for id field instead of document ID.

I tried also to read all Book documents and filter by ID in Python, but I have maaany books, so that's not an option.

books = firestore.Client.collection_group('books').get()
book = [b.id for b in books if b.id == my_id]

And I cannot define a specific path to the document, because I have multiple stores.

What can I do?

Rafaó
  • 591
  • 3
  • 14

1 Answers1

0

If you want to query for a document ID, you can use the FieldPath.document_id() operator.

So that'd look something like (not a Pythonista here):

.where(FieldPath.document_id(), "==", my_id)

Also see:

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • hm, it doesn't seem to work... I'm printing my collection group and there is my `Book`, but filtering it with what you suggested gives me nothing :( In the answer you linked there's not a comparison to a string (like in my case), but to a document or a collection... – Rafaó May 05 '22 at 15:28
  • Given this answer: https://stackoverflow.com/a/56150650/4034593 I don't think that's possible, what I'm trying to do :( I think that's crucial that I'm working with collection group, not a single collection. – Rafaó May 05 '22 at 16:16
  • 1
    Aha, right... I forgot that in collection group indexes the `documentId` actually contains the entire path of the document (as the document ID alone might not be unique). In that case I don't think it is possible to query this way, unless you also include the document ID in the document itself. – Frank van Puffelen May 05 '22 at 16:21
  • "document ID might not be unique" answers the question. Thanks Frank! – Rafaó May 05 '22 at 16:31