Database Reference
In-Depth Information
Using Keys and Values
Documents are made up of keys and values. Let's take another look at the example
discussed previously in this chapter:
{
"firstname": "Peter",
"lastname": "Membrey",
"phone_numbers": [
"+852 1234 5678",
"+44 1234 565 555"
]
}
Keys and values always come in pairs. Unlike an RDBMS, where every field must
have a value, even if it's NULL (somewhat paradoxically, this means unknown ), MongoDB
doesn't require that a document have a particular value. For example, if you don't know
the phone number for a particular person on your list, you simply leave it out. A popular
analogy for this sort of thing is a business card. If you have a fax number, you usually put
it on your business card; however, if you don't have one, you don't write: “Fax number:
none.” Instead, you simply leave the information out. If the key/value pair isn't included
in a MongoDB document, it is assumed not to exist.
Implementing Collections
Collections are somewhat analogous to tables, but they are far less rigid. A collection is a
lot like a box with a label on it. You might have a box at home labeled “DVDs” into which
you put, well, your DVDs. This makes sense, but there is nothing stopping you from
putting CDs or even tapes into this box if you wanted to. In an RDBMS, tables are strictly
defined, and you can only put designated items into the table. In MongoDB, a collection
is simply that: a collection of similar items. The items don't have to be similar (MongoDB
is inherently flexible); however, once we start looking at indexing and more advanced
queries, you'll soon see the benefits of placing similar items in a collection.
While you could mix various items together in a collection, there's little need to do
so. Had the collection been called media , then all of the DVDs, CDs, and tapes would be
at home there. After all, these items all have things in common, such as an artist name,
a release date, and content. In other words, it really does depend on your application
whether certain documents should be stored in the same collection. Performance-wise,
having multiple collections is no slower than having only one collection. Remember:
MongoDB is about making your life easier, so you should do whatever feels right to you.
Last but not least, collections are effectively created on demand. Specifically, a
collection is created when you first attempt to save a document that references it. This
means that you could create collections on demand (not that you necessarily should).
Because MongoDB also lets you create indexes and perform other database-level
commands dynamically, you can leverage this behavior to build some very dynamic
applications.
 
Search WWH ::




Custom Search