Home » Software Development » MongoDB » MongoDB Collection Example

About Yatin

Yatin
The author is graduated in Electronics & Telecommunication. During his studies, he has been involved with a significant number of projects ranging from programming and software engineering to telecommunications analysis. He works as a technical lead in the information technology sector where he is primarily involved with projects based on Java/J2EE technologies platform and novel UI technologies.

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

In MongoDB, the first basic step is to have a database and collection in place. The database is used to store all of the collections, and the collection in turn is used to store all of the documents. In this article, you will learn:

  • Creating a database
  • Creating a collection

2.1 Creating a MongoDB Database

In MongoDB, There is no CREATE DATABASE statement in MongoDB like there is in SQL. Creating a database in MongoDB is as simple as issuing the using command. The following example shows how this can be done:

Fig. 1: MongoDB Database Creation Command

Fig. 1: MongoDB Database Creation Command

Code Explanation:

  • The use command is used to create a database in MongoDB. If the database doesn’t already exist, a new one will be created

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

Fig. 2: MongoDB Database Creation Output

Fig. 2: MongoDB Database Creation Output

Note: MongoDB will automatically switch to the database once created.

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

The easiest way to create a collection is to insert a record (which is nothing but a document consisting of Field Names and Values) into a collection. If the collection does not exist a new one will be created. The following example shows how this can be done:

Fig. 7: MongoDB Create Collection Using Insert Command

Fig. 7: MongoDB Create Collection Using Insert Command

Code Explanation:

  • The first part of the command is the insert statement which is the statement used to insert a document into the collection
  • The second part of the statement is to add the Field name and the Field value, in other words, what is the document in the collection going to contain

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

Fig. 8: MongoDB Creation Collection Using Insert Output

Fig. 8: MongoDB Creation Collection Using Insert Output

The output shows that the operation performed was an insert operation and that one record was inserted into the 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
(No Ratings Yet)
Start the discussion Views Tweet it!

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

 

Leave a Reply

avatar
  Subscribe  
Notify of