One thing about MongoDB that can be seen as a positive or negative is its schema-less design. This allows for a variable number of properties in a document and the ability to add or remove properties at any time. A schema-less design provides a lot of flexibility for changing requirements and evolving object state. However it can make it harder to create a well structured database. With more power comes more responsibility!
Now let's get started creating a MongoDB database that represents different Christmas trees. Once you have MongoDB installed, you can run the
mongo command in bash to start up the database and CLI. It is important to know that MongoDB has three logical groupings; databases, collections, and documents. Databases are not the same as a traditional RDBMS database connection - they are simply groupings (namespaces) for collections and documents4. Collections are a way to group documents together in MongoDB, similar to tables in an RDBMS.
To start, I made a new database for Christmas trees. The
use <database> command changes the current database.
This command does not create a database yet. To do that I need to add some collections and documents. I added a document to a collection called
The document JSON is passed as an argument to the
insert() function on the
tree collection object. The
find() function can be used to view all the documents in the tree collection.
This code sample shows the ability to chain functions. The second function
pretty() will format the JSON in an easily readable fashion.
Let's say I want to add more properties to the tree document. Since MongoDB collections have no schema, any properties can be added!
I used the
update() function on the collection to edit a document. The first parameter queries the collection and matches with a document. The second parameter defines what to update. The
$set property binds the specified properties in the document to the given values5.
EDITOR variable to
vim in bash.
Now in the MongoDB shell I defined a function to edit in Vim:
Using the name of this function, I began editing in Vim with the
createTree function so that it inserts another document into the tree collection. Once the function was finalized, I saved the file and quit vim.
Back in the MongoDB CLI the functions contents can be viewed by typing
createTree. The function is executed by typing
Now the tree collection contains two documents. What if I wanted to add the properties
buyer_id to the existing documents? I could use the
update() function, however it only matches with the first document it finds. To match all documents that fit certain query conditions, the
updateMany() function is used.
1000 as a parameter to this function, invoking it one thousand times. When I checked to see the number of trees in tree collection, I got 1003 as expected.
find() function also accepts JSON, it is easy to count all the trees of type Frazier with a height between 6-7 feet: