12

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.

  • 1
    Your first snippet executes a query against the `lists` subcollection of the `user1` document in the `users` collection. So if you have many users, each with their own lists, only the lists of `user1` are queried. – Frank van Puffelen Jan 09 '18 at 22:30
  • Possible duplicate of [Firestore query subcollections](https://stackoverflow.com/questions/46573014/firestore-query-subcollections) – apaatsio May 11 '19 at 12:48

2 Answers2

16

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.

Tom Bailey
  • 682
  • 5
  • 12
8

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.

apaatsio
  • 3,073
  • 1
  • 22
  • 18
  • 7
    Can I get all the `lists` subcollections but not from **all** documents, but only if the document ID is in a documents ID list that I supply? – Alaa M. Jul 18 '20 at 10:29
  • just do `query(collection(firestore, "collection", "specific_id", "sub-collection"))` – leopragi May 06 '22 at 07:20