MongoDB – embedded documents

Suppose we have a document representing a person and later on are provided with his/her address information. We have a design choice to create 2 separate documents or to link the two by nesting the secondary data (address) into the primary document (person)

{
“name” : “Stuart Hayes”,
“address” : {
“street” : “Addison Road”,
“county” : “Kent”,
“country”: “UK”
}
}

We could even make use of an array for ‘horizontal’ data

{
“name” : “Stuart Hayes”,
“address” : {
“street” : “Addison Road”,
“county” : “Kent”,
“country”: “UK”,
“phone numbers” : [“07813 241 390”, “home not provided”, null]
}
}

You can begin to feel how working with embedded documents and denormalsing may provide a more natural representation of the data. In an RDBMS, these would probably be modelled as two separate rows in two separate tables (tbl_people, tbl_addresses), although in the eventual presentation layer, they may be flattened into a star-schema. I’m wondering if this sort of model wouldn’t work well as the end data presentation layer – a sort of flattened structure/star-schema.

The flip-side of this is more data repetition within MongoDB. If the normalised wold, if an address changed and we processed the change in the 3NF DB and then we joined tbl_people and tbl_address, we’d get the updated address cascading for all people at the changed address. In this embedded example, we’d have to update the address in each person’s document.

A post on querying within arrays is here

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s