Introducing MongoDB Chapter 3
Why MongoDB?
MongoDB provides a lot of advantages, some of which are:
Flexible documents: A MongoDB collection holds several documents. Each
document under one collection can have variable field names and can have a
different size as well, which means we don't have to define the schema.
No complex relationships: The documents in MongoDB are stored as JSON
documents, which means we no longer have to scratch our head learning about
the relationships between various components of the application.
Easy to scale: MongoDB is easy to scale as it minimizes the database size by
using a partitioning method called sharding. Sharding is a database partitioning
method that allows us to segregate a large database into smaller pieces.
MongoDB queries
We did quickly review what Mongo queries look like in Chapter 1, Introduction to MEVN.
Here, we will dive deep into these queries.
The first thing we need to do is start the MongoDB server. We can do that with this
command:
$ mongod
Now, let's open the mongo shell by typing mongo in our Terminal. When we enter the
mongo shell, to display the list of databases, we type show dbs.
If you see the database in the list, type use {database_name} to start using this database.
If we haven't created our database yet, just using use {database_name} will create a
database for us. It's as simple as that. For this exercise, let's create a database called
mongo_test_queries. So for that, we need to use:
> use mongo_test_queries
This should output the following in the Terminal:
# switched to db mongo_test_queries
Now, once we enter the database, the first thing that we need is a collection. We have a
database but there are no collections. The best way to create a collection in MongoDB is by
inserting a document. This not only initializes a collection but also adds the document to
that collection. Simple as that. Now, let's move on to Mongo queries.