Reputation:
In MySQL, I create a user table, give the table a field "userid", assign each new user an unique id with AUTO_INCREMENT. Then, i distribute additional information about a user over several tables, each of those has a field "userid" ...
What is the equivalent of this pattern in MongoDB?
What data object would I use to create a reference between several documents that belong somehow together?
Upvotes: 0
Views: 540
Reputation: 69703
MongoDB does not have auto-increment, because auto-increment doesn't work well when you have a distributed cluster of independent machines. The equivalent for this are the unique ObjectIDs MongoDB assigns to each document. They are much longer than integers, but they are guaranteed to be globally unique so they can be used as distinct identifiers.
MongoDB has no support for JOINs. When you need them, you need to emulate them on the application layer. That means you should usually avoid distributing data about one entity over multiple documents. The usual solution is to embed all the data as sub-objects or in arrays in the parent-document. Doing this in SQL is a bad idea, but MongoDBs query language and indexing system is made for this and supports it really well.
Example: When you have an invoice with n positions, you would have two SQL tables, invoice_head
and invoice_position
. In MongoDB, you would have one collection invoices
where each document has an array of positions.
There is, however, one exception to this. MongoDB doesn't like objects which grow over time. For performance reasons, MongoDB tries to keep every document in a consecutive section of the hard drive. That means when a document grows to exceed that section, it needs to be reallocated. This constant reallocation can be a real performance hook. Very large objects are also bad for caching. To further discourage growing objects, MongoDB imposes an artificial size limit of 16MB per document.
Example: When you have a forum where each user has n posts, you would not embed the posts in the document of the user who wrote them or in the document of the thread they belong to, because these documents would then grow and grow over time and might some day hit the 16MB limit.
Upvotes: 3