Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
255 views
in Technique[技术] by (71.8m points)

google cloud firestore - Should pesistent data be stored in a subCollection or a collection?

Imagine you store a bunch of activities in a collection. Some users can choose whether or not to participate in a given activity. If a user decides to participate in an activity a document in a subCollection participants in the activityDoc is created with the uId of the user. Then imagine the activity needs to be deleted and created again with some new information, but the participants subCollection should not change at all. Because the activityDoc is deleted the participants subCollection needs to be copied to the new activityDoc and deleted from the old activityDoc.

Would it be more write/delete efficient if a new separate collection (not a subCollection of an activityDoc) was created, and in this collection all the information about the participants of each activity is stored. In this way the data would not need to be copied when the activityDoc was deleted. Would it hurt performance if the collection ended up being very very big (thousands of documents)?

question from:https://stackoverflow.com/questions/65915722/should-pesistent-data-be-stored-in-a-subcollection-or-a-collection

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

TLDR: Yes, this is a classical case where the data should be added to a separate collection instead of a subcollection.

Imagine you have N participant documents under an activity that needs to be re-created, first you would have to read every participant document, delete the parent activity, recreate it and recreate all of the N participant documents again, so you would basically have:

N reads + (1 + N) writes + (1 + N) deletions

Against only 1 write + 1 deletion with the separate collection approach. depending on the number of participants this a big cost on your Firestore bill.

A couple of things to consider are

  1. Make sure to keep the same ID of the activity document, that way you don't have to touch the reference to it in the participant documents

  2. The participant document can have an array of acitivies it is participating in, which would make it easier to operate, so something like this:

    PARTICIPANT DOCUMENT
        uid: "UID VALUE"
        activities: [activityId1, activityId2, ..., activityIdN]
        otherField
        ...
        otherFieldN
    

With this approach if you want to add a participant to a new activity all you have to do is add the activityId to that array using an arrayUnion.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...