Database Reference
In-Depth Information
explored and explained in the next two chapters, which discuss querying and updat-
ing, respectively.
4.3
Nuts and bolts: on databases, collections,
and documents
We're going to take a break from the e-commerce example to look at some of the core
details of using databases, collections, and documents. Much of this involves defini-
tions, special features, and edge cases. If you've ever wondered how MongoDB allo-
cates data files, which data types are strictly permitted within a document, or what the
benefits of using capped collections are, read on.
4.3.1
Databases
A database is a logical and physical grouping of collections. In this section, we'll dis-
cuss the details of creating and deleting databases. We'll also jump down a level to see
how MongoDB allocates space for individual databases on the file system.
M ANAGING DATABASES
There's no explicit way to create a database in MongoDB. Instead, a database is cre-
ated automatically once you write to a collection in that database. Have a look at this
Ruby code:
@connection = Mongo::Connection.new
@db = @connection['garden']
Assuming that the database doesn't exist already, the database has yet to be created on
disk even after executing this code. All you've done is instantiate an instance of the
class Mongo::DB . Only when you write to a collection are the data files created. Con-
tinuing on:
@products = @db['products']
@products.save({:name => "Extra Large Wheel Barrow"})
When you call save on the products collection, the driver tells MongoDB to insert the
product document into the garden.products namespace. If that namespace doesn't
exist, then it's created; part of this involves allocating the garden database on disk.
To delete a database, which means dropping all its collections, you issue a special
command. You can drop the garden database from Ruby like so:
@connection.drop_database('garden')
From the MongoDB shell, you run the dropDatabase() method:
use garden
db.dropDatabase();
Do be careful when dropping databases; there's no way to undo this operation.
Search WWH ::




Custom Search