Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to perform collection group query using document ID in Cloud Firestore

So few day ago I moved my apps posts to cloud firestore from realtime database because of the more flexable querying that firestore apparently has. I have been modifying my code to work with firestore as the new database. Now I ran into a problem. How can I retrieve every document within "Posts" collection that has "Likes" collection that contains a specifically named document? I don't know if that makes sense so here's an image showcasing the problem:

enter image description here

I had a working query for firebase realtime database but can't figure out how to do it with firestore. Is it possible or do I have to change the structure of my database? If I do have to change the structure, what would be the most convenient way of getting the same result?

like image 911
Aapo Vainonen Avatar asked May 17 '19 14:05

Aapo Vainonen


People also ask

How do I query multiple collections in firestore?

Firestore does not have the concept of server-side joins or projections across collections. Each query or document read can only take data from a single collection, or from all collections that have the same name with collection group queries.

Can two documents have the same ID in firestore?

You cannot have several documents with the same ID in one Collection: a document ID must be unique across a collection.

How do I find the number of documents in a collection firestore?

If you need a count, just use the collection path and prefix it with counters . As this approach uses a single database and document, it is limited to the Firestore constraint of 1 Update per Second for each counter.


Video Answer


1 Answers

This is currently not possible with collection group queries. You might be tempted to put a filter on the query for FieldPath.documentId() == 'your-doucment-id', but that just isn't supported. FieldPath.documentId() is actually a token that refers to to fully unique document id, which includes the entire path of the document.

The workaround is to store the document ID as a field in the document, and filter on the contents of that field instead. So, if the document had a field called id with the ID of the document, you could query for collectionGroup("Likes").whereEquals('id', 'your-document-id').

like image 67
Doug Stevenson Avatar answered Oct 18 '22 17:10

Doug Stevenson