This question already has answers here:
What are the benefits of using a root collection in Firestore vs. a subcollection?
(2 answers)
Closed 7 months ago.
I am working on a quiz game, where players have to answer questions of different categories (sports, music, .....). Right now, I have two different ideas how to store these categories /questions in Firestore:
Creating a new Root-level collection for each category. Every document in this collection would define a question of that category. Stcuture would look like this:
user_collection
user_1_document
user_2_document
user_X_document
music_questions_collection
music_questions_1_document
music_questions_2_document
music_questions_X_document
sports_questions_collection
sports_questions_1_document
sports_questions_2_document
sports_questions_X_document
Creating ONE Root-level collection and create a document inside this collection for each category, where each document contains a subcollection of questions:
user_collection
user_1_document
user_2_document
user_X_document
category_collection
music_document
music_question_subcollection
music_question_document_1
music_question_document_2
music_question_document_3
sports_document
sports_question_subcollection
sports_question_document_1
sports_question_document_2
sports_question_document_3
I have already read about some advantages and limitations of subcollections and root-collections, but have not found enough information regarding read-costs and speed for this specific use case. Can anyone give me some information about drawbacks and advantages of the two listed approaches.
I have not found enough information regarding read-costs and speed for
this specific use case. Can anyone give me some information about
the drawbacks and advantages of the two listed approaches?
In terms of "read-costs and speed", the two approaches are equivalent: using a root collection or a sub-collection is exactly the same.
As a matter of fact, from a technical perspective, a root collection and one of its sub-collections are not at all related to each other. They just share a part of their path but nothing else.
So, since you store the same documents in either a root collection or a sub-collection (i.e. same number of docs in each category collection and same field structure for these docs), there is no difference.
Related
I have quiz game and I want to add 1000 questions on firebase firestore and I have thousands of users in my game and every user has special id.
What is the best way to know if the user answered this question before or no?
Should I add user id inside every question who answered it or there is the another way?
I want build data structure logically for reduce consumptionmy read limit on firestore.
The two most common solutions I can quickly think of:
Create a single top-level collection answers, where you store all answers for all users. In that collection use the combination of UID and question ID to name each document, so that you can check if a document /answers/$uid+$questionID exists.
Create a top-level collection users in which each UID represents a user. Under each UID document create sub-collection answers, where you use the question ID to name the documents. Now you can check for each user if they answered a specific question, by checking /users/$uid/answers/$questionId.
Neither of these is pertinently better than the other, and they typically allow for similar use-cases. I'd usually pick the second structure simply because it results in a more natural distribution of the data, but it's s pretty small preference in practice.
This question already has answers here:
Firestore: Does querying a collection also includes their sub collection?
(2 answers)
Closed 3 years ago.
I have collection users which have a sub collection called "notes about". "Notes about" have security rules that only users with role - "manager" can access them. Now everything works nice and so on, but my problem starts when manager decides to update his name, surname or imageUrl.
Since all notes have also property called "addedBy" which contains user name, surname, id and imageUrl, I need to go through all users and all their notes about sub collection documents, so I can check each document and update it with cloud function.
So far looks like I will have to refactor my db and store "notes about" in a separate collection. But maybe there is a way to get all collection documents with all their sub collection documents in another (reasonable) way.
I would prefer not to refactor my DB but maybe that's the only solution at the moment.
What are your thoughts?
DB model:
But maybe there is a way to get all collection documents with all their sub collection documents in another (reasonable) way.
Unfortunately there isn't. Queries in Firestore are shallow, they only get items from the collection that the query is run against. There is no way to get documents from a top-level collection and other subcollections in a single query. Firestore doesn't support queries across different collections in one go. A single query may only use properties of documents in a single collection. IMO, you can go ahead by querying the database multiple times to get the desired values. Is not so slow as might think.
Another possible solution in your case might be to use collection group query. In order to use this new feature, all the subcollections shoould have the same name.
Now it's up to you to decide if you'll use more than one query to get the data, or use collection group query or even refactor the database to fit your needs.
This question already has answers here:
How to list subcollections in a Cloud Firestore document
(4 answers)
Closed 5 years ago.
I am reading the docs and see that FireStore allows sub-collection. Which is great. Consider the following example as mentioned here int he docs.
As shown in the docs I can get the reference to the last doc as follows
var messageRef = db.collection('rooms').doc('roomA')
.collection('messages').doc('message1');
In the above example, the id's for docs and collections are typed in.
There are cases when id's are dynamically generated. In such a case how can I know how many collections a doc has? Or whether a doc has any sub-collections. How can I do that?
On mobile clients, you can't know how many collections or what collections a document has. There is just no API for that. You have to know ahead of time what collections may exist for a document, or accept that a query on an unknown subcollection may return no documents.
I'm quite new to NoSQL, that's why I come here to get your opinions.
I'm trying to understand if it's better to use nested object or subcollections in a specific case. I will try to explain my case.
I have to store several shops in my Db. Each shop will have an address, a phone number etc... So I have a Collection "Shop" and inside several Documents representing the shops.
Now, my shops have some contacts (2,3 or 4 employees for example). My question is, what should I do :
Store in my "shop" documents 2,3 or 4 objects like :
objectContact: {
name: "Georges",
age: 20....
}
Create a subcollections "Contact" inside my "shop" documents, and then insert 2,3 or 4 documents in this subcollections.
Which is the better ? Does one of this two solutions disable some tools/queries in NoSQL ? Does one of this two solutions is faster when it comes to write/read the data ?
Thanks in advance,
Currently, all the queries in the cloud firestore are shallow which means you can't get the subcollection with its collection.You have read it separately. So I would recommend you to store it in a nested document. But it has few limitations though. Check this link for detailed explanation of modelling data in cloud firestore
The firestore docs don't have an in depth discussion of the tradeoffs involved in using sub-collections vs top-level collections, but do point out that they are less flexible and less 'scalable'. Given that you sacrifice flexibility in setting up your data in sub-collections, there must be some definite plus sides besides a mentally satisfying structure.
For example how does the time for a firestore query on a single key across a large collection compare with getting all items from a much smaller collection?
Say we want to query a large collection 'People' for all people in a family unit. Alternatively, partition the data by family in the first place into family units.
People -> person: {family: 'Smith'}
versus
Families -> family: {name:'Smith'} -> People -> person
I would expect the latter to be more efficient, but is this correct? Are the any big-O estimates for each?
Any other advantages of sub-collections (eg for transactions)?
I’ ve got some key points about subcollections that you need to be aware of when modeling your database.
1 – Subcollections give you a more structured database.
2 - Queries are indexed by default: Query performance is proportional to the size of your result set, not your data set. So does not matter the size of your collection, the performance depends on the size of your result set.
3 – Each document has a max size of 1MB. For instance, if you have an array of orders in your customer document, it might be a good idea to create a subcollection of orders to each customer because you cannot foresee how many orders a customer will have. By doing this you don’t need to worry about the max size of your document.
4 – Pricing: Firestore charges you for document reads, writes and deletes. Therefore, when you create many subcollections instead of using arrays in the documents, you will need to perform more read, writes and deletes, thus increasing your bill.
To answer the original question about efficiency:
Querying all people with the family 'Smith' from the people top-level collections really is not any slower than asking for all the people in the 'Smith' family sub-collection.
This is explained in the How to Structure Your Data episode of the Get to Know Cloud Firestore video series.
There are some trade-offs between top-level collections and sub-collections to be aware of. Depending on the specific queries you intend to use you may need to create composite indexes to query top-level collections or collection group indexes to query sub-collections. Both these index types count towards the 200 index exemptions limit.
These trade-offs are discussed in detail near the bottom of the Understanding Collection Group Queries blog post and in Maps, Arrays and Subcollections, Oh My! episode of the Get to Know Cloud Firestore video series.
I've linked to the relevant parts of both videos.
I was wondering about the same thing. The documentation mainly talks about arrays vs sub-collections. My conclusion is that there are no clear advantages of using a sub-collection over a top-level collection. Sub collections had some clear technical limitations before, but I think those are removed with the recent introduction of collection group queries.
Here are some advantages of both approaches:
Sub collection:
Your database "feels" more structured as you will have less top-level collections listed.
No need to store a reference/foreign key/id of the parent document, as it is implied by the database structure. You can get to the parent via the sub collection document ref.
Top-level collection:
Documents are easier to delete. Using sub collections you need to make sure to first delete all sub collection documents before you delete the parent document. There is no API for this so you might need to roll your own helper functions.
Having the parent id directly in each (sub) document might make it easier to process query results, depending on the application.
Todd answered this in firebase youtube video
1) There's a limit to how many documents you can create per minute in
a single collection if the documents have an always-increasing value
(like a timestamp)
2) Very large collections don't do as well from a
performance standpoint when you're offline. But they are generally
good options to consider.