MongoDB Collection Example
Hello, in this tutorial we will see a study and understand the implementation of the collection in MongoDB. The idea is to understand how MongoDB works and deploy a highly scalable and performance-oriented database.
1. Introduction
MongoDB is a document-oriented NoSQL database used for high volume data storage and provides high performance, high availability and automatic scaling.
1.1 What is MongoDB?
- MongoDB is a document database where each database contains collections which in turn contains documents. Each document can be different with varying number of fields. The size and content of each document can be different from each other and stored in a JSON-like format, Binary JSON (BSN) in MongoDB
- The rows (or the documents as called in MongoDB) doesn’t need to have a schema defined beforehand. Instead, the fields can be created on the fly
- Data model available within MongoDB allows developers to represent hierarchical relationships, store arrays, and other more complex structures more easily
- MongoDB environments offers scalability
1.2 What is NoSQL?
NoSQL Database is used to refer a non-SQL or non-relational database concepts.
- Provides a mechanism for storage and retrieval of data other than tabular relations model used in relational databases
- Provides more flexibility since all records are not restricted to the same column names and types defined across the entire table
- Do not use SQL language to query data and provides no strict schema
- With NoSQL, ACID (Atomicity, Consistency, Isolation, Durability) properties of database transactions are not guaranteed
- Offers scalability and high performance for handling huge volumes of data
1.3 Why to use MongoDB?
Below are some of the reasons why someone should start using MongoDB:
- Document-oriented: Since MongoDB is a NoSQL type database, instead of having data in a relational type format, it stores the data in documents. Thus, making MongoDB very flexible
- Ad hoc queries: MongoDB supports searching by field, range queries, and regular expressions searches. It often provides queries to return specific fields within documents
- Indexing: Indexes can be created to improve the performance of searches within MongoDB
- Automatic Load Balancing: MongoDB uses the concept of sharding to scale horizontally by splitting data across multiple MongoDB instances
- Replication: MongoDB can provide high availability with replica sets
1.4 Advantages Over RDBMS
Below are some of the key term differences between MongoDB and RDBMS:
RDBMS | MongoDB | Difference |
Table | Collection | In RDBMS, the table contains the columns and rows which are used to store the data whereas, in MongoDB, this same structure is known as a collection. The collection contains documents which in turn contains Fields, which in turn are key-value pairs |
Row | Document | In RDBMS, the row represents a single, implicitly structured data item in a table. In MongoDB, the data is stored in documents |
Column | Field | In RDBMS, the column denotes a set of data values. These in MongoDB are known as Fields |
Joins | Embedded documents | In RDBMS, data is sometimes spread across various tables and in order to show a complete view of all data, a join is sometimes formed across tables to get the data. In MongoDB, the data is normally stored in a single collection, but separated by using embedded documents. So there is no concept of joins in MongoDB |
Primary Key | _id | In MongoDB, the primary key is automatically set to the _id field |
Apart from the terms differences, a few other differences are shown below:
- Relational databases are known for enforcing data integrity. This is not an explicit requirement in MongoDB
- RDBMS requires that data be normalized first so that it can prevent orphan records and duplicates, thus resulting in more table joins and requiring more keys and indexes. This leads to performance issues which again is not an explicit requirement in MongoDB
1.5 Download and Install MongoDB
You can watch this video in order to download and install the MongoDB database on your Windows operating system.
Now, open up the MongoDB workbench and let’s start building the collection in a NoSQL database!
2. MongoDB Collection Example
As stated earlier, in MongoDB a database is used to store collections, and each collection is used to store documents. Lets dive in on how to create your first database and collection.
2.1 Creating a MongoDB Database
There is no CREATE DATABASE
statement in MongoDB like there is in SQL. To create a database we need to use the use
command as shown below:
Note: If the database already exists, a new one will not be created!
Upon successful execution, the following output is shown:
Note: We get switched to the newly created database automatically.
2.2 Creating a MongoDB Collection
A MongoDB collection is a grouping of MongoDB documents. A collection is the equivalent of a table which is created in any other RDMS such as Oracle or MySQL. A collection exists within a single database and doesn’t enforce any sort of structure.
2.2.1 Two Ways to Create a Collection
Here are two ways of creating collections:
- Developers can also create a collection explicitly, using the
createCollection()
method - Developers can create a collection on the fly when inserting a document (using the
insert()
) method
Using the createCollection() Method
Developers can also create collections using the createCollection()
method. This allows you to create a collection without inserting a document. Here is an example of using the createCollection()
method:
If the command is executed successfully, the following output will be shown:
Developers can also specify options keyword for the collection by using the db.createCollection(name, options)
syntax. Here is an example:
If the command is executed successfully, the following output will be shown:
The options fields available as of MongoDB version 3.2 are as follows:
Field | Type | Description |
---|---|---|
capped | boolean | When set to true , creates a capped collection. A capped collection is a fixed-sized collection that automatically overwrites its oldest entries when it reaches its maximum size. If you specify true , you must also set a maximum size in the size field |
autoIndexId | boolean | Specify false to disable the automatic creation of an index on the _id field. As of MongoDB version 3.2, this field is deprecated, and it will be removed in version 3.4 |
size | number | Maximum size in bytes for a capped collection. Only used with capped collections (it is ignored in other collections) |
max | number | Maximum number of documents allowed in the capped collection. Note that the size field takes precedence over the max field. If the collection reaches its size limit before the document limit has been reached, MongoDB will remove documents anyway |
Using the insert() Method
A very convenient method for creating a collection is to directly insert a document into one. If it does not exist, a new one will be created automatically as shown in the example code below:
Notes:
db.painters
We define the collection (regardless if it exists) to add documents to.- We use the insert statement to insert a document into the predefined
painters
collection. - We directly define document data in the form of comma separated name/value pairs.
Upon successful execution, the following output is shown:
WriteResult({ "nInserted" : 1 })
dictates that a write operation was executed, and that a single record was inserted into the newly created painters
collection.
The insert command can also be used to insert multiple documents into a collection at one time. The below code example can be used to insert multiple documents at a time. The following example shows how this can be done:
- Create a JavaScript variable called
myGuitarist
to hold the array of documents - Add the required documents with the Field Name and values to the variable
- Use the insert command to insert the array of documents into the collection
If the command is executed successfully, the following output will be shown:
2.3 Show MongoDB Collections
To check the created collection, use the command show collections
. Here is an example:
2.4 Drop MongoDB Collections
In MongoDB, db.collection_name.drop()
method is used to drop a collection from the database. It completely removes a collection from the database and does not leave any indexes associated with the dropped collections.
The db.collection_name.drop()
method does not take any argument and produce an error when it is called with an argument. Here is an example:
Now, check the collections in the database.
Note: The drop command returns true if it successfully drops a collection. It returns false when there is no existing collection to drop.
3. Conclusion
The main goal of this article is to discuss the MongoDB features and an introduction to MongoDB Collections. Overall speaking, I found MongoDB very powerful and easy to use. I look forward to using MongoDB with Node.js and will share my experience in future blogs.
4. Download the MongoDB Files
This was an example of MongoDB Collection. Run the script and the result will be printed in the console window.
You can download the full source code of this example here: MongoDB Collection Example