Note: Querying across subcollections is not currently supported in Cloud Firestore. If you need to query data across collections, use root-level collections.
When I read the documentation for me it's not clear if it's possible to do something like this:
var listsRef = db.collection("users/user1/lists");
var query = listsRef.where("public", "==", true);
I can understand that it's not supported if I try to do this:
var listsRef = db.collection("users/{userId}/lists");
var query = listsRef.where("public", "==", true);
But I am wondering if I can query in a specific collection that comes from a specific document. In fact, what's the difference here and in a root collection?
Thanks in advance.
To read a single document, we can use DocumentReference's get() method that returns a Task<DocumentSnapshot>, while reading multiple documents from a collection or Query, we can use Firestore Query's get() method that returns an object of type Task<QuerySnapshot>. Both methods read the data only once.
collectionGroup('foo') – firestore will query all the collections (and subcollections) present everywhere with the name foo to fetch the documents. // db. collectionGroup('foo'). get() will get both fooA and fooB >> foo (collection) > fooA (document) field1: ...
The SDK now supports this
Please see the other answers below...
Old answer
You can query on a subcollection as long as you know the document it belongs to. For example the following is a valid subcollection query:
const usersCollection = firestore.collection("users");
const adminDocument = usersCollection.doc("admin");
const adminsFollowersQuery = adminDocument.collection("followers").where("name", "==", "Arthur Dent");
adminsFollowersQuery.get().then((adminsFollowers) => {
adminsFollowers.docs.forEach((adminFollower) => {
console.log(adminFollower.get("name"));
});
});
As you point out the following is NOT currently valid:
const allUserFollowersQuery = firestore.collection("users/{wildcard}/followers")
.where("name", "==", "Arthur Dent");
adminsFollowersQuery.get().then((allUserFollowers) => {
allUserFollowers.docs.forEach((follower) => {
console.log(follower.get("name"));
});
});
I think the documentation here is a little confusing but by "Querying across subcollections" they mean, you can query a specific subcollection, as above, but you cannot query general subcollections. At least not as a single action using the FireStore SDK.
Firebase now supports querying subcollections (as of May 2019).
You can do this
db.collectionGroup("lists").where("public", "==", true)
which will return matching lists
documents for all users.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With