Firestore - subcollection query for a specific document

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.

Upvotes: 12

Views: 18849

Answers (2)

Tom Bailey
Tom Bailey

Reputation: 702

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.

Upvotes: 16

apaatsio
apaatsio

Reputation: 3793

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.

Upvotes: 8

Related Questions