Reputation: 3093
I'm using MongoDB for the first time, and I'm not entirely sure what the best practice would be in the situation I'm in. Here's what I'm trying to do:
I'm making an iPhone app where people can create an event and then chat about it (in order to iron out some details, lets say). I have a collection for the events. I'm not sure how I should store the users' chats though. I want a chat to be linked to its corresponding event, but I'm not sure how to do that given that MongoDB is not relational.
Should I just create another collection/document for the chats and link(I mean the MongoDB linking) it to the event?
Upvotes: 3
Views: 3448
Reputation: 109
While designing your db schema, always keep in mind the size limit of a document. For countable-infinitely growing sub-documents, its best to store it in a different collection. This would hold true for comments, chats, etc inside a parent post. Hope this helps.
Upvotes: 1
Reputation: 4002
A key question when designing a MongoDB schema is when to embed and when to link. Embedding is the nesting of objects and arrays inside a BSON document. Links are references between documents.
This is how the official MongoDB schema design documentation starts.
When designing for a document database there are a couple of things to keep in mind:
Reading the MongoDB doc I've pointed and answering the above questions would give you the final answer.
Upvotes: 8
Reputation: 30136
I would embed the chats within the Event document.
It seems like the chat will always be referred to in the context of the event and therefore it makes sense to have it embedded inside so that it can be easily accessed.
The implications for performance are more subtle. Some things to consider:
If you were to go with the embedded approach, when a document is retrieved, the chat would already be contained within it. Therefore, a subsequent query would not be needed to retrieve the chats. This makes accessing chats fast but also potentially makes retrieving the event documents slower (as they are larger). You can, however, exclude the fields you don't need (which makes the performance equivalent to that of the scenario with two different collections)
If you need to work with the chats in a different context than that of the event, it may be necessary to one day use a separate collection. However the decision to embed them now seems sound and you can always write a simple script to move them to their own collection.
Hope that helps, cheers!
Upvotes: 8
Reputation: 7351
I would start with the simplest approach and design a collection of events where each chat post would be an embedded document. Lately you could move chats to a different collection if it need in case of performance.
Upvotes: 1