I’m attempting to perform a complex query with firestore v9. My intention is to get some docs (skip and limit) from a my data structure. What I mean is, I need to get for example 5 docs from a doc -> collections -> doc. and this docs need to be order by there date.
So for example, lets say in my array I contain 2 docs id ['e4z3HNyUCQbiYQRzfVO4RyebMCP2', 'WZImI6tl0IUFKbICEZzcciaUxKG2']
, from this 2 docs, I would need to get their userPosts ordered by the creation date, but I would need to pass a skip and limit too. So from this 2 docs, I would limit 3 docs to get, but these 3 docs will be from the 2 posts ids I passed.
const queryBuild = await query(
collection(db, 'posts'),
where('userPosts', 'in', [`post.id`...]),
collection(db, 'userPosts'),
...
);
const querySnapshot = await getDocs(queryBuild);
2
Answers
There is no out-of-the-box way to do what you are looking for with Firestore.
You will need to issue two queries, one for each of the two parent document.
Let say, for example, that in total you only want 3 documents from the two sub-collections.
You first query the first subcollection with the following query:
You then query the second subcollection with the following query:
Then you merge the two results (i.e. push the documents of the two
QuerySnapshot
s in one Array), order them by descendingcreation
value and take the first three ones.An alternative to Renaud’s answer would be to store the
postId
of the parent document in eachuserPost
. With that you could add anin
clause to a collection group query to get the user posts of up to 10 parent documents.If you have more than 10 IDs, you’ll need to perform multiple of such queries, so you’d be back to a similar approach as in Renaud answers, just with 1/10th as many API calls.