Firestore query to retrieve users based on last connection and presence of field

I have a Firestore collection called users that contains user documents. Each user document has an optional field called previewPosts, which is an array representing the user’s four most recent posts. Additionally, there is another field called lastConnection that stores the timestamp of the user’s last online connection.

I want to implement a query on the users collection that retrieves the top 10 users based on their last connection and ensures that they have the optional previewPosts field defined with at least one post in the array.

How can I construct a Firestore query to achieve this?

I have tried the following:

const query = firestore
  .collection("users")
  .orderBy("lastConnection", "desc")
  .orderBy("previewPosts");

Is creating an extra field the best approach?

  const query = firestore
    .collection("users")
    .where("hasPreviewPhotos", "==", true)
    .orderBy("lastConnection", "desc");

>Solution :

Yes, creating an extra field is likely the best way. You could make it be a count rather than a boolean if you wanted to order by how many previews rather than just the existence, and this would later allow you to filter based on the number too (say "only users with more than 2 previews").

Leave a Reply