firebasevue.jsgoogle-cloud-firestorevuetify.js

Firestore Group by field


Below is my firestore collection structure

enter image description here

My vue method to get data

fetchResults(){
  db.collection('data').onSnapshot((querySnapShot)=>{
    let results = [];
    querySnapShot.forEach(doc=>{
      results.push(doc.data())
    })
    this.record=results;
  })
}

What I want is to query in the document like group by ID and order by sec_id desc.

How do I suppose to query like that?

So that I will get document grouped by ID field.


Solution

  • As of October 2022, you can do aggregation queries with count, sum, and max.


    Original answer:

    As a NoSQL type database, Cloud Firestore doesn't offer any aggregation queries such as grouping, sum, max, etc. You have to perform these operations in your client code. For your case, this means you will have to query for all the documents in the collection, then group them by whatever fields you want. Alternatively, you can maintain a separate collection of pre-grouped documents to satisfy your query. (Duplicating data like this is common in NoSQL type databases.)