iDecode
iDecode

Reputation: 28876

How to get the parent document ID of a subcollection when using CollectionGroup queries?

I'm using collection group query but I'm unable to get the parent document ID.

collection
  document1
    subC
      doc1
  document2
    subC
      doc2

On running a query I want to get the name of parent document, i.e. document1, document2, etc but it returns me doc1 and doc2. This is my query:

var col = FirebaseFirestore.instance.collectionGroup('subC').where('foo', isEqualTo: 'bar');
var snapshot = await col.get();
for (var doc in snapshot.docs) {
  print(doc.id); // Prints doc1, doc2
}

Upvotes: 3

Views: 1799

Answers (1)

iDecode
iDecode

Reputation: 28876

doc.id returns the underlying document ID. You need to first get the current DocumentReference (doc1, doc2), using that get CollectionReference (subC) and then get its parent which is your document1 and document2.

So, you need this:

var col = FirebaseFirestore.instance.collectionGroup('subC').where('foo', isEqualTo: 'bar');
var snapshot = await col.get();
for (var doc in snapshot.docs) {
  print(doc.reference.parent.parent?.id); // Prints document1, document2
}

Upvotes: 7

Related Questions