1

I am trying to get multiple documents in my database that have been created with the same id. I know it's possible to do it using collectionGroup with the code presented bellow, but I am looking for a potentially more efficient and cleaner way to do it.

I have read this question How to perform collection group query using document ID in Cloud Firestore indicating that it is essential to store the id in a field to find the document by using collectionGroup.

In my case, documents with myId can be in two different collections so I want to avoid using collectionGroup because I would have to do it on two separate collections like this:

const collectionOneDocs = await firestoreInstance.get().collectionGroup('collectionOne').where('id', '==', myId).get();
const collectionTwoDocs = await firestoreInstance.get().collectionGroup('collectionTwo').where('id', '==', myId).get();

This code works for me, but I would like to do a single operation to access the documents and also avoid saving the id as a field in the documents since it's not really necessary. So is there anyway in firestore to find all documents with a specific id or is this already the best solution available with firestore?

Thanks a lot!

someRandomDev
  • 561
  • 6
  • 15
  • Answer below. But I'm not sure I understand why you don't want to have a single collection group. The whole purpose of their existence is so that you can query across multiple collections by giving them the same name. – Frank van Puffelen Oct 18 '20 at 20:21
  • @FrankvanPuffelen thanks for the answer. I understand their purpose, but our DB is currently designed in a way that I need to query on those two group of collections with different names and changing this would take a lot of time so I was looking for an alternative solution. I'll just use the collectionGroup twice since it appears to be the best here. Thanks again for the answer. – someRandomDev Oct 18 '20 at 20:35

1 Answers1

1

If the collections have different names, there's no way to get results from them with a single query.

So your only options are to:

  • Either run a separate query for each collection (name).
  • Give the collections the same name.
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807