Santiago
Santiago

Reputation: 982

MondoDB - Why should you embed a document inside a document

Im looking to use MongoDB for my database implementation. Why would you want to embded a document insode a document?

Upvotes: 1

Views: 317

Answers (2)

anon
anon

Reputation:

In simple terms, embed if its NOT a top level object, if it does NOT have complex relationships, if there will be a lot of duplicate data if you do NOT embed, and if your documents become bigger then a few megabytes.

Taken from the MongoDB site: http://www.mongodb.org/display/DOCS/Schema+Design

Summary of Best Practices

  • Embed "First class" objects, that are at top level, typically have their own collection.
  • Line item detail objects typically are embedded.
  • Objects which follow an object modelling "contains" relationship should generally be embedded.
  • Many to many relationships are generally done by linking.
  • Collections with only a few objects may safely exist as separate collections, as the whole collection is quickly cached in application server memory.
  • Embedded objects are a bit harder to link to than "top level" objects in collections.
  • It is more difficult to get a system-level view for embedded objects. When needed an operation of this sort is performed by using MongoDB's map/reduce facility.
  • If the amount of data to embed is huge (many megabytes), you may reach the limit on size of a single object. See also GridFS.
  • If performance is an issue, embed.

Upvotes: 2

Thilo
Thilo

Reputation: 262534

It is one way to do what in a relational database you would do with a JOIN (something that you cannot do in MongoDB).

For example, you could have a MongoDB document as a blog post, and embed the list of comments right in there.

Then you can (for example):

  • load post and comments in a single query
  • search for posts which have replies
  • search for posts by user A which have replies by user B
  • atomically update both post and comments in a single transaction

All that would be impossible (or at least difficult) if the comments were stored in their own collection as separate documents.

Upvotes: 4

Related Questions