MongoDB

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?

  1. 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
  2. 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
  3. Data model available within MongoDB allows developers to represent hierarchical relationships, store arrays, and other more complex structures more easily
  4. MongoDB environments offers scalability

1.2 What is NoSQL?

NoSQL Database is used to refer a non-SQL or non-relational database concepts.

  1. Provides a mechanism for storage and retrieval of data other than tabular relations model used in relational databases
  2. Provides more flexibility since all records are not restricted to the same column names and types defined across the entire table
  3. Do not use SQL language to query data and provides no strict schema
  4. With NoSQL, ACID (Atomicity, Consistency, Isolation, Durability) properties of database transactions are not guaranteed
  5. 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:

  1. 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
  2. Ad hoc queries: MongoDB supports searching by field, range queries, and regular expressions searches. It often provides queries to return specific fields within documents
  3. Indexing: Indexes can be created to improve the performance of searches within MongoDB
  4. Automatic Load Balancing: MongoDB uses the concept of sharding to scale horizontally by splitting data across multiple MongoDB instances
  5. 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:

RDBMSMongoDBDifference
TableCollectionIn 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
RowDocumentIn RDBMS, the row represents a single, implicitly structured data item in a table. In MongoDB, the data is stored in documents
ColumnFieldIn RDBMS, the column denotes a set of data values. These in MongoDB are known as Fields
JoinsEmbedded documentsIn 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_idIn MongoDB, the primary key is automatically set to the _id field

Apart from the terms differences, a few other differences are shown below:

  1. Relational databases are known for enforcing data integrity. This is not an explicit requirement in MongoDB
  2. 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:

Fig. 1: MongoDB Database Creation Command
Fig. 1: MongoDB Database Creation Command

Note: If the database already exists, a new one will not be created!

Upon successful execution, the following output is shown:

Fig. 2: MongoDB Database Creation Output
Fig. 2: MongoDB Database Creation Output

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:

Fig. 3: MongoDB Create Collection Command
Fig. 3: MongoDB Create Collection Command

If the command is executed successfully, the following output will be shown:

Fig. 4: MongoDB Creation Collection Output
Fig. 4: MongoDB Creation Collection Output

Developers can also specify options keyword for the collection by using the db.createCollection(name, options) syntax. Here is an example:

Fig. 5: MongoDB Creation Collection with Options Command
Fig. 5: MongoDB Creation Collection with Options Command

If the command is executed successfully, the following output will be shown:

Fig. 6: MongoDB Creation Collection with Options Output
Fig. 6: MongoDB Creation Collection with Options Output

The options fields available as of MongoDB version 3.2 are as follows:

FieldTypeDescription
cappedbooleanWhen 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
autoIndexIdbooleanSpecify 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
sizenumberMaximum size in bytes for a capped collection. Only used with capped collections (it is ignored in other collections)
maxnumberMaximum 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:

Fig. 7: MongoDB Create Collection Using Insert Command
Fig. 7: MongoDB Create Collection Using Insert Command

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:

Fig. 8: MongoDB Creation Collection Using Insert Output
Fig. 8: MongoDB Creation Collection Using Insert Output

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

Fig. 9: MongoDB Create Collection Using Array
Fig. 9: MongoDB Create Collection Using Array

If the command is executed successfully, the following output will be shown:

Fig. 10: MongoDB Create Collection Using Array Output
Fig. 10: MongoDB Create Collection Using Array Output

2.3 Show MongoDB Collections

To check the created collection, use the command show collections. Here is an example:

Fig. 11: Show MongoDB Collections
Fig. 11: Show MongoDB Collections

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:

Fig. 12: Drop MongoDB Collection
Fig. 12: Drop MongoDB Collection

Now, check the collections in the database.

Fig. 13: Show MongoDB Collections after Drop Function
Fig. 13: Show MongoDB Collections after Drop Function

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.

Download
You can download the full source code of this example here: MongoDB Collection Example

Yatin

An experience full-stack engineer well versed with Core Java, Spring/Springboot, MVC, Security, AOP, Frontend (Angular & React), and cloud technologies (such as AWS, GCP, Jenkins, Docker, K8).
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button