Reputation: 1314
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.
Upvotes: 4
Views: 18894
Reputation: 317467
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.)
Upvotes: 15
Reputation: 1162
I'm too late, but if anyone looking for easier solution, I would suggest you to use lodash for grouping, in below example I'm grouping sales based on the Order Date.
import { mapValues, groupBy, omit } from "lodash";
export const salesTrend = async () => {
const orderData: any[] = [];
const orderResponse = await getDocs(collectionRef);
const orders = orderResponse.docs
orders.forEach(order => orderData.push(order.data()))
let grouped = mapValues(groupBy(orderData, 'orderDate'),
clist => clist.map(car => omit(car, 'orderDate'))
);
console.log(grouped);
}
Upvotes: 0
Reputation: 61
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
Upvotes: 1
Reputation: 712
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
Upvotes: 2