I am wondering why aggregation (like SUM) is not built into Firestore when other NoSQL databases like MongoDB has them. Is it inherent to the design of firebase? Do you think it can be added soon?
CodePudding user response:
This is a good question, actually.
Firestore was built for some certain use cases, that are not the use cases MongoDB is built for. MongoDB can be used for a lot of use cases, even those covered by Firestore.
Basically, the main idea behind the dev team was that they wanted to build a document database, easy to use, managed and lightweight. This led to making it without features like shardings, or aggregations, and so on, but still, the dev team knew some of them would be useful. So they decided to leverage the possibilities offered by a cloud platform, and built it to support everything the platform (Firebase) could offer: Firebase Functions.
So, in the end, the answer is:
- no, Firestore will never support aggregation functions. Or at least, that's not in the plans, as for now;
- it is still possible to obtain a SUM, using a Firebase Function that will trigger everytime you perform a write operation, so you can update the SUM value. You'll need to store the value somewhere else in your firestore database, but that's a pretty good solution, and it is even documented here as an example. Only thing you have to remind is: the sum value will be "eventually consistent". It means that there could be instants when the persisted value is different from the real value, because the trigger is yet to fire, or because the function that will update the value has yet to finish, but this is the way Google designed Firestore and Firebase, so it's a good practice and pattern we can use.