Firestore Group by field

限于喜欢 提交于 2020-07-30 12:51:10

问题


Below is my firestore collection structure

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.


回答1:


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.)




回答2:


You can do using

fetchResults(){
  db.collection('data')
 .orderBy("id", "asc")
 .onSnapshot((querySnapShot)=>{
     // Do something
  })
}

More information visit https://firebase.google.com/docs/firestore/query-data/order-limit-data and you can also apply filter using click on click on filter icon




回答3:


Instead of calculating the data with an aggregate query, the data should be saved in the document itself using client side logic to update the aggregate data each time the document is changed or use cloud functions.

See this post from Google blog.

https://firebase.google.com/docs/firestore/solutions/aggregation



来源:https://stackoverflow.com/questions/57831837/firestore-group-by-field

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!