Relationship Between Collections/Tables: MongoDB

In this video tutorial we shall learn about normalization, and the way mongoDB handles relationship between two collections(Primary Key and Foreign Key concept in RDBMS)

Normalization: It refers to the process of organizing the data to minimize redundancy and dependency.

There is no 1 way of doing this in mongoDB. You could implement it according to the needs of your application.

For Example, Normalization is good in the application wherein we do more of write operation. De-normalization is good, wherein we only read.

In today’s tutorial, we shall see how we can implement relationship between two collections/tables and query the database using this relationship.

Database name: company
Collections: info, ceo

mongoDB-database-collection

info collection

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
>use company
switched to db company
 
>db.info.find().forEach(printjson)
{
"_id" : ObjectId("517e829d005b19f1f0d96b25"),
"name" : "Apple",
"product": "iPhone5S",
"emp_no" : 100
}
 
{
"_id" : ObjectId("517e8377005b19f1f0d96b26"),
"name" : "Technotip",
"product": "Video Tutorials - Educational",
"emp" : [
"Satish",
"Kiran"
],
"Videos" : {
"mongo" : "MongoDB Videos",
"php": "PHP Video Tutorials"
}
}

Create another collection ceo and insert a document

1
2
3
4
5
6
7
8
9
10
>db.ceo.insert({
      name      : "SATISH",
      company_id: db.info.find()[1]._id
});
>db.ceo.find().forEach(printjson)
{
        "_id" : ObjectId("51822e2c60e925795355fd26"),
        "name" : "SATISH",
        "company_id" : ObjectId("517e8377005b19f1f0d96b26")
}

Here we store the _id value present in the second record of info collection inside first record’s company_id field of ceo collection.
This way we build a relation between two collections info and ceo.

Next, we query mongoDB to get some results based on this relationship.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
> db.info.find({ _id: db.ceo.find()[0].company_id }).forEach(printjson)
{
        "_id" : ObjectId("517e8377005b19f1f0d96b26"),
        "name" : "Technotip",
        "product" : "Video Tutorials - Educational",
        "emp" : [
                "Satish",
                "Kiran"
        ],
        "videos" : {
                "mongo" : "MongoDB Videos",
                "php" : "PHP Video Tutorials"
        }
}
>

This command(in first line) retrieves the document in the ‘info’ collection which matches the company_id value present in ceo collection and _id of info collection.

Primary Key and Foreign Key Concept in MongoDB


[youtube https://www.youtube.com/watch?v=7cYT0Qbu9tU]

YouTube Link: https://www.youtube.com/watch?v=7cYT0Qbu9tU [Watch the Video In Full Screen.]



Note: In traditional database systems(RDBMS) we accomplish the same by using primary key and foreign key concept. And make use of JOINS (Equi JOIN, RIGHT JOIN, LEFT JOIN) to query the database, which actually consumes more time and resources. In mongoDB, there is no need of JOIN’s and hence is faster than RDBMS.

ObjectId ( _id ) as Primary Key: MongoDB

In this video tutorial we shall learn more about ObjectId( _id ) of MongoDB document.

ObjectId is a primary key in any mongoDB document.
We can’t change document id once it has been created and inserted.
If we do not explicitly assign value to _id, then it’ll be automatically assigned and inserted.
We can’t have same document id for more than 1 document.

These ObjectId’s are of BSON datatype.
It’s a 12-byte value.

Basically, each _id is a combination of ..
– Time the document/record was saved/inserted
– Host name of the machine/server it’s running on
– Process id of the server process
– and a random incremental number

Example documents

mongoDB-collection-document

Since the ObjectId‘s are formed taking time of insertion of document into consideration, we can extract this time using getTimestamp() method.

1
db.info.find()[0]._id.getTimestamp()

Custom _id values
We can explicitly define the _id value and in such case system won’t add it for us.

1
2
3
4
5
db.info.insert({
   _id    : 2,
   name   : "Google",
   product: "Google Glass"
})

output

1
2
3
4
5
6
>db.info.find().forEach(printjson)
{
"_id"    : 2,
"name"   : "Google",
"product": "Google Glass"
}

If you insert ObjectId yourselves, then having a separate ‘document_created_at’ field becomes necessary depending on your application requirements.

For that, you can use a inbuilt method Date()

1
2
> new Date()
ISODate("2013-05-01T07:55:12.467Z")

Date is actually a class, but it calls upon the constructor method, hence returning current system/server timestamp, in ISO format.

Remove / Delete / Drop Document

1
db.info.remove({ _id: 2 })

To remove a document, simply pass in a unique { key: value } pair and the document gets deleted/removed.

Primary Key in MongoDB: ObjectId


[youtube https://www.youtube.com/watch?v=YCZV5N01Oqs]

YouTube Link: https://www.youtube.com/watch?v=YCZV5N01Oqs [Watch the Video In Full Screen.]



Navigation of Documents
To navigate between documents, use the index numbers, and to select particular field use it’s key name.

To get the _id of first document

1
db.info.find()[0]._id

0 is the index of first document or record. _id is the field/key name.

Create and Insert Documents: MongoDB

In this video tutorial, we’ll look at the basic differences between MongoDB and traditional Database Management Systems. Also, commands to create database, collection, documents – insertion.

Topic of discussion:
Key differences.
Keyword differences.
Schema-free collection.
Database creation.
Creation of Collection.
Insertion of Documents.
JavaScript Console/Shall.

Some Commands

Show Database Already Present

1
show dbs

Create Database

1
use company

In MongoDB, it’ll never actually create any database or collection until we start storing documents in it!

Point object ‘db’ to our new database, by switching to company database

1
2
3
4
>use company
Switched to db company 
>db
company

Naming our Collection

1
db.info

So our collection name is info

Number of documents present

1
db.info.count()

using count() method, we check the no of documents present inside info collection.

Inserting document into Collection

1
2
3
4
5
db.info.insert({
 name     : 'Apple',
 product  : 'iPhone5S',
 emp_no   : 100
});

This inserts our first record.
insert() is the method, which accepts key-value pair object as it’s parameter.

JavaScript Shall
Since, this is a JavaScript shall, we can write any valid JavaScript code and interact directly with MongoDB.

Lets see another method to insert documents into the same collection.

Using save method

1
2
3
4
5
6
7
8
9
>var data = {}
>data.name = 'Technotip IT Solutions'
>data.product = 'Video Tutorials - Educational'
>data.emp = [ 'Satish', 'Kiran' ]
>data.videos = {}
>data.videos.mongo = 'MongoDB videos'
>data.videos.php = 'PHP Video Tutorials'
 
>db.info.save(data);

We create a JSON object data.
We start storing { key: value } pair into it.
emp is an array, which contains name of 2 employees.
videos is a sub object.

Now using save method we insert this data object into info collection.

Save()
Save() is a higher lever method. It checks to see if the object we’re inserting is already present in our collection, by checking the _id value we’re inserting. _id field(which is a primary key in MongoDB document)
– If there is no matching _id field in a document, it’ll call insert method and insert the data. And if the data being entered has no _id value, insert() method will create _id value for us, and insert the data into the collection.
– If _id matches to any document in our collection, it’ll use update() instead to update the previously present data with the new data entered by the user.

Database, Collections, Documents: MongoDB


[youtube https://www.youtube.com/watch?v=yAjG_fC6fPU]

YouTube Link: https://www.youtube.com/watch?v=yAjG_fC6fPU [Watch the Video In Full Screen.]



Note:
There is no Schema for our collection. i.e., no column name and datatype.
Since documents are in BSON format, insertion and finding data is much faster.

Schema-free design is flexible and is of much use in modern day web application.

Example: Users upload photos and tag names of people in the pic. This can be stored as an array of tags in a key value pair, for only those pics which has tags. For other pics, we need not create this array itself. This is flexible. Also BSON format helps create application with high Scalability.

MongoDB – Getting Started Guide

MongoDB is one of the leading NoSQL database.

NoSQL is some what misleading name, which now means Not Only SQL!

The basic intention for NoSQL database is to scale modern web databases and to facilitate solving the complex data storage( and structuring ) requirements of modern day web applications.

MongoDB is a Document-Oriented Database System and is Schema-free.
Here the Document is a BSON document.
BSON is Binary JSON.

JSON stands for JavaScript Object Notation
– It’s a fat-free alternative to XML.
– JSON is a lightweight data-interchange format.

To learn JSON
(look only at JSON format)
Objects, Arrays: JSON Using jQuery
Fetch JSON Array Elements Using jQuery AJAX Method: getJSON

MongoDB and BSON
MongoDB can be considered as a giant array of JSON objects, since the documents are in binary JSON format, insertion and searching will be much faster.

MongoDB – is Schema-Free
– There is no predefined structure. i.e., There’ll be no column name and predefined datatype.

MongoDB – Getting Started Guide


[youtube https://www.youtube.com/watch?v=J2qnq8WI6EU]

YouTube Link: https://www.youtube.com/watch?v=J2qnq8WI6EU [Watch the Video In Full Screen.]



Downloading and Installing: MongoDB
Goto MongoDB official website, click on Downloads link and select the 64-bit version for your OS and download it. Note that, 32-bit version has some limitations. Look for the MongoDB official documentations for more details.

Once you have the download file, unzip it.

If you’re on Windows OS, then create a folder C://data/db which will be used by MongoDB software.

To start using MongoDB, goto MongoDB folder, inside Bin, you can find mongod.exe – click on it, and leave it to run.
Next click on mongo.exe and start passing the instructions/commands.

Note: mongo.exe is a JavaScript shall / console, so we’ll be writing JavaScript to work directly with mongodb database.