Quick Reference Study Notes for MongoDB 3.x (Foundation)

 MongoDB 3.x

 

Overview:

MongoDB is a database which came into light around the mid-2000s.

It is an open-source document database and leading NoSQL database. MongoDB is written in C++. MongoDB is a cross-platform, document oriented database that provides, high performance, high availability and easy scalability.MongoDB works on collection and document.

Database

Database is a physical container for collections. Each database gets its own set of files on the file system. A single MongoDB server can store multiple databases.

Collection

Collection is a group of MongoDB documents. A collection is the equivalent of a table which is created in any other RDMS such as Oracle or MS SQL. A collection exists within a single database. Collections do not enforce any structure. Documents within a collection can have different fields.

Document

A document is a set of key-value pairs. Documents have dynamic schema. Dynamic schema means that documents in the same collection do not need to have the same set of fields or structure. Common fields in a collection's documents may hold different types of data.

_id – This is a field required in every MongoDB document. It represents a unique value in the MongoDB document. The _id field is like the document's primary key.


RDBMS terminology with MongoDB

 

 RDBMS         

 MongoDB      

Database

Database

Table

Collection

Tuple/Row

Document

column

Field

Primary Key

Primary key

Table join

Embedded Documents


 

Structure:

Following example shows the document structure of a blog site, which is a comma-separated key-value pair.

 

{
  _id: Course_id
  name: TITLE_OF_COURSE,
  duration: COURSE_DURATION,
  tags: [TAG1, TAG2, TAG3],
  enrollments: TOTAL_Enrollments,

 instructor: instructor name,
  enrollments: [
     {
        course:'Course_ID',
        user: USER_ID,
        dateOfEnrollment: DATE_TIME,
     },
     {
        course:'Course_ID',
        user: USER_ID,
        dateOfEnrollment: DATE_TIME,
     }

  ]
}

_id is a 12 bytes hexadecimal number which assures the uniqueness of every document. We can provide _id while inserting the document. If we don’t provide then MongoDB provides a unique id for every document.

First 4 bytes for the current timestamp,

next 3 bytes for machine id,

next 2 bytes for process id of MongoDB server and

remaining 3 bytes are simple incremental VALUE.

 

Advantages of MongoDB

  1. Schema less − MongoDB is a document database in which one collection holds different documents. Number of fields, content and size of the document can differ from one document to another.

  2. Structure of a single object is clear.

  3. No complex joins.

  4. Deep query-ability. MongoDB supports dynamic queries on documents using a document-based query language that's nearly as powerful as SQL.

  5. Ease of scale-out − MongoDB is easy to scale.

  6. Uses internal memory for storing the (windowed) working set, enabling faster access of data.

 

Why Use MongoDB ?

 

1. Document Oriented Storage − Data is stored in the form of JSON style documents.

2. Index on any attribute

3. Replication and high availability.

4. Auto-sharding.

5. Rich queries.

6. Professional support by MongoDB.


 

Example:

Suppose a client needs a database design for his e-learning website and see the differences between RDBMS and MongoDB schema design. Website has the following requirements.

  • Every course has the unique instructor.

  • Every course can have one or more enrollments.

  • Every course has its price,duration and instructor.

  • Every course has some tags.

In RDBMS schema, design for above requirements will have minimum three tables.

 

enrollments

courses

tag_lists

Users

Columns:

  • Course_id

  • User_id

  • Date_time_enrollment

Columns:

  • Id

  • name

  • price

  • instructor

Columns:

  • id

  • Course_id

  • tag

Columns:

  • id

  • name

  • email

 

While in MongoDB schema, design will have one collection course and the following structure −

{
  _id: Course_id
  name: TITLE_OF_COURSE,
  duration: COURSE_DURATION,
  tags: [TAG1, TAG2, TAG3],
  enrollments: TOTAL_Enrollments,
  enrollments: [
     {
        course:'Course_ID',
        user: USER_ID,
        dateOfEnrollment: DATE_TIME,
     },
     {
        course:'Course_ID',
        user: USER_ID,
        dateOfEnrollment: DATE_TIME,
     }

  ]
}

So while showing the data, in RDBMS you need to join three tables and in MongoDB, data will be shown from one collection only.

How to create a database in MongoDB

MongoDB use DATABASE_NAME is used to create database. The command will create a new database if it doesn't exist, otherwise it will return the existing database.

>use mydb
switched to db mydb

 

If you want to check your databases list, use the command show dbs.

>show dbs
local     0.78125GB
test      0.23012GB

 

Your created database (mydb) is not present in list. To display database, you need to insert at least one document into it.

>db.movie.insert({"name":"study section"})
>show dbs
local      0.78125GB
mydb       0.23012GB
test       0.23012GB

In MongoDB default database is test. If you didn't create any database, then collections will be stored in test database.

 

How to Drop a database in MongoDB

MongoDB db.dropDatabase() command is used to drop a existing database.

db.dropDatabase()

 

This will delete the selected database. If you have not selected any database, then it will delete default 'test' database.

 

The createCollection() Method

MongoDB db.createCollection(name, options) is used to create collection.

db.createCollection(name, options)

 

Parameter

type

description

Name

string

Name of the collection to be created.

Options

document

Specify options about memory size and indexing.

 

>db.createCollection("mycollection")

You can check the created collection by using the command show collections.

>show collections
mycollection
system.indexes

>db.createCollection("mycol", { capped : true, autoIndexId : true, size :
  6142800, max : 10000 } )

In MongoDB, you don't need to create collection. MongoDB creates collection automatically, when you insert some document.

>db.tutorialspoint.insert({"name" : "tutorialspoint"})
>show collections
mycol
mycollection
system.indexes
tutorialspoint
>

The drop() Method

MongoDB's db.collection.drop() is used to drop a collection from the database.

db.COLLECTION_NAME.drop()

 

The insert() Method

>db.COLLECTION_NAME.insert(document)

>db.mycol.insert({
  _id: ObjectId(7df78ad8902c),
  name: 'MongoDB Overview',
  duration: '5 hrs',
  price: 50,
  tags: ['mongodb', 'database', 'NoSQL']
  })

The find() Method

To query data from MongoDB collection, you need to use MongoDB's find() method.

>db.COLLECTION_NAME.find()



* NOTE: "This study material is collected from multiple sources to make a quick refresh course available to students." 

This website uses cookies to improve user experience. By using our website you consent to all cookies in accordance with our Cookie Policy. More info. I Agree