Firestore - Sorting data based on internal data of firestore collection document

Viewed 112

I am developing chat application using Firestore with very simple structures which include groups and number of unread messages also. I want to sort groups with unread messages first (User wise) & then others. I'm looking for a way but not found yet.

Here are the 2 ways which I am trying to follow to get what I want but have not any way.

  1. By Keeping my message and status per user in same doc.
  2. By keeping message_status in some other collection with required info and some query.

Group structure -

{
     group_name: "GROUP-NAME",
     group_id: "MESSAGE-GROUP-ID",
     admin: "Anuj",
     participants: [
          1,2
     ],
     participants_status: [
          {
              id: 1,
              active: 1 // true (User active)
          },
          {
              id: 2,
              active: 0 // false (User not active)
          },
    ],
    message_status_user_wise: [
          {
              user_id: 1, // ID of participant
              unread_message_count: 1 
          },
          {
              user_id: 2, // ID of participant
              unread_message_count: 5
          }
    ]
}

Message structure -

{
     message: "This is test message"
     group_id: "MESSAGE-GROUP-ID",
     sender: "Anuj",
     sender_id: 1
}

Now there will be multiple groups and with unread/read messages. Now question is how I can query to sort and get the groups which are having unread messages on top ie. - Groups having unread_message_count > 0 of any user should come on top in results.

Similarly, I have some other questions also regarding to it -

  1. Keeping the same structure, How Can I get total unread message count of all groups?
  2. How I can get only those groups in which some user having any id is active?

I also looked at subcollections, i.e also none of my use.

0 Answers
Related