Load Data From External JavaScript File: MongoDB

This video tutorial illustrates loading data to mongoDB server from an external JavaScript file ( Writing script for MongoDB shall )

Here, we write a simple JavaScript file and using command prompt we load the contents of JavaScript file into new Database.

import-data

JavaScript file
load.js – in path: C:/temp/load.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
db.person.insert({
name:'Satish',
age:25,
skills:['nodejs', 'mongoDB', 'HTML5']
});
 
db.person.insert({
name:'Kiran',
age:27,
skills:['PHP', 'mySQL', 'HTML5']
});
 
db.person.insert({
name:'Sunitha',
age:24,
skills:['html', 'ASP']
});

Here we’re inserting some data/record/documents into the collection person.

Database’s Before running the script

1
2
3
4
5
6
7
8
9
10
11
12
13
C:\>cd mongodb
 
C:\mongodb>cd bin
 
C:\mongodb\bin>mongo
MongoDB shell version: 2.4.3
connecting to: test
> show dbs
admin   0.203125GB
company 0.203125GB
local   0.078125GB
> exit
bye

Before running the script, we have only 3 databases.

Running the script

1
2
3
C:\mongodb\bin>mongo 127.0.0.1/satish C:/temp/load.js
MongoDB shell version: 2.4.3
connecting to: 127.0.0.1/satish

Here, mongo is the JavaScript shall.
127.0.0.1 is nothing but our localhost.
satish is the new database we are creating.
C:/temp/load.js is the path of load.js file.
We’re loading the contents of load.js file into new database satish.

Database’s After running the script

1
2
3
4
5
6
7
8
9
10
11
12
13
C:\mongodb\bin>mongo
MongoDB shell version: 2.4.3
connecting to: test
> show dbs
admin   0.203125GB
company 0.203125GB
local   0.078125GB
satish  0.203125GB
> use satish
switched to db satish
> show collections
person
system.indexes

New database satish has been added and it has person collection, which we loaded from the JavaScript file.

Documents/records In person 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
25
26
27
28
29
30
> db.person.find().forEach(printjson)
{
        "_id" : ObjectId("518b62443cbad352108c321b"),
        "name" : "Satish",
        "age" : 25,
        "skills" : [
                "nodejs",
                "mongoDB",
                "HTML5"
        ]
}
{
        "_id" : ObjectId("518b62443cbad352108c321c"),
        "name" : "Kiran",
        "age" : 27,
        "skills" : [
                "PHP",
                "mySQL",
                "HTML5"
        ]
}
{
        "_id" : ObjectId("518b62443cbad352108c321d"),
        "name" : "Sunitha",
        "age" : 24,
        "skills" : [
                "html",
                "ASP"
        ]
}

Using find() method we display all its contents.

This way we could load application data from an external JavaScript file.

Writing script for MongoDB shall


[youtube https://www.youtube.com/watch?v=ygK2zE1-k0w]

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



Note:
This method will be handy while migrating our application from one mongoDB server to another mongoDB server.
There is import/export options in mongoDB, but this method is also helpful if we have some custom data to be inserted. nontheless a useful tool to have.

SELECT Columns/Fields: MongoDB

In this video tutorial we shall see selecting of key: value in MongoDB.

In RDBMSs like MySQL, we do the same using SELECT statement.
In MongoDB, we use findOne() and find() methods.

key-value-pair-mongoDB

Documents in ‘info’ collection

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
> 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"
        }
}

Learn Create and Insert Documents: MongoDB.

Note:
find() returns cursor objects.
findOne() returns single object.

We can use findOne() method to select and retrieve only one record at a time.

findOne() Method

1
2
3
4
5
6
7
8
> db.info.findOne({name: 'Technotip'}).product
Video Tutorials - Educational
 
> db.info.findOne({name: 'Technotip'}).videos
{ "mongo" : "MongoDB Videos", "php" : "PHP Video Tutorials" }
 
> db.info.findOne({name: 'Technotip'}).emp;
[ "Satish", "Kiran" ]

Syntax for retrieving normal {key: value} pair, sub-object {key: value} pair and array {key: value} pair is same.

Limitation
Using findOne() method, we could select and return only 1 {key: value} pair.

To select and return more than 1 {key: value} pair, we can make use of find() method, with 2 parameters.

SELECT Columns or Fields ( { KEY: VALUE } ): MongoDB


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

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



find() Method, with two parameters

1
2
> db.info.find({name: 'Apple'}, {product: 1}).forEach(printjson);
{ "_id" : ObjectId("517e829d005b19f1f0d96b25"), "product" : "iPhone5S" }

First parameter is the condition, second parameter specifies the {key: value} pairs.

We can pass more than 1 key in second parameter; that would returns multiple {key: value} pairs.

1
2
3
4
5
6
> db.info.find({name: 'Apple'}, {product: 1, emp_no: 1}).forEach(printjson);
{
        "_id" : ObjectId("517e829d005b19f1f0d96b25"),
        "product" : "iPhone5S",
        "emp_no" : "100"
}

1 or true means, those {key: value} pairs need to be returned.
0 or false means, excluding those {key: value} pairs, all other {key: value} pairs(records) needs to be returned.

true(0)

1
2
3
4
5
6
7
8
> db.info.find({name: 'Apple'}, {product: true}).forEach(printjson);
{ "_id" : ObjectId("517e829d005b19f1f0d96b25"), "product" : "iPhone5S" }
> db.info.find({name: 'Apple'}, {product: true, emp_no: true}).forEach(printjson);
{
        "_id" : ObjectId("517e829d005b19f1f0d96b25"),
        "product" : "iPhone5S",
        "emp_no" : "100"
}

False(0): Exclusion

1
2
> db.info.find({name: 'Apple'}, {product: 0, emp_no: 0}).forEach(printjson);
{ "_id" : ObjectId("517e829d005b19f1f0d96b25"), "name" : "Apple" }

Note:
True and False combination doesn’t work

1
2
3
4
5
6
7
8
9
10
11
12
> db.info.find({name: 'Apple'}, {product: true, emp_no: false}).forEach(printjson);
Wed May 08 12:11:30.184 JavaScript execution failed: error: {
        "$err" : "You cannot currently mix including and excluding fields. 
                  Contact us if this is an issue.",
        "code" : 10053
} at src/mongo/shell/query.js:L128
> db.info.find({name: 'Apple'}, {product: 0, emp_no: 1}).forEach(printjson);
Wed May 08 12:11:40.840 JavaScript execution failed: error: {
        "$err" : "You cannot currently mix including and excluding fields. 
                  Contact us if this is an issue.",
        "code" : 10053
} at src/mongo/shell/query.js:L128

We can not combine true(1) and false(0) together in the second parameter.

Special Provision!
But we can do it with _id(ObjectId)

1
2
3
> db.info.find({name: 'Apple'}, 
               {product: 1, emp_no: 1, _id: 0}).forEach(printjson);
{ "product" : "iPhone5S", "emp_no" : "100" }

Operation of second document/record in ‘info’ collection.
This illustrates that the syntax for sub-objects, array and the normal key/value pair is same.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
> db.info.find({name: 'Technotip'}, {product: 1}).forEach(printjson);
{
        "_id" : ObjectId("517e8377005b19f1f0d96b26"),
        "product" : "Video Tutorials - Educational"
}
{ "_id" : ObjectId("518363e2d73694e289255486") }
> db.info.find({name: 'Technotip'}, {product: 1, videos: 1}).forEach(printjson);
 
{
        "_id" : ObjectId("517e8377005b19f1f0d96b26"),
        "product" : "Video Tutorials - Educational",
        "videos" : {
                "mongo" : "MongoDB Videos",
                "php" : "PHP Video Tutorials"
        }
}
 
> db.info.find({name: 'Technotip'}, 
               {product: 1, videos: 1, emp: 1}).forEach(printjson);
{
        "_id" : ObjectId("517e8377005b19f1f0d96b26"),
        "product" : "Video Tutorials - Educational",
        "emp" : [
                "Satish",
                "Kiran"
        ],
        "videos" : {
                "mongo" : "MongoDB Videos",
                "php" : "PHP Video Tutorials"
        }
}
 
> db.info.find({name: 'Technotip'}, 
               {product: 1, videos: 1, emp: 1, _id: 0}).forEach(printjson);
{
        "product" : "Video Tutorials - Educational",
        "emp" : [
                "Satish",
                "Kiran"
        ],
        "videos" : {
                "mongo" : "MongoDB Videos",
                "php" : "PHP Video Tutorials"
        }
}

Note:
Two documents with same name

1
2
3
4
5
6
7
8
9
10
11
12
13
14
{
        "_id" : ObjectId("517e8377005b19f1f0d96b26"),
        "name" : "Technotip",
        "product" : "Video Tutorials - Educational",
        "emp" : [
                "Satish",
                "Kiran"
        ],
        "videos" : {
                "mongo" : "MongoDB Videos",
                "php" : "PHP Video Tutorials"
        }
}
{ "_id" : ObjectId("518363e2d73694e289255486"), "name" : "Technotip" }
1
2
> db.info.findOne({name: 'Technotip'})._id;
ObjectId("517e8377005b19f1f0d96b26")

If we use findOne() method on this collection, and the condition being the name key, then the oldest document will be returned.
Only one key: value pair is returned, as findOne() returns only single object.

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.

Insertion of Records into Database: PHP & MySQL

Video tutorial illustrates INSERTION of records into database via PHP script.

Simple / basic insertion operation:

First connect to the database.

Next, using simple MySQL query.
index.php

1
2
3
4
5
6
7
8
9
< ?php
include_once('db.php');
 
 
if(mysql_query("INSERT INTO apple VALUES('','Oracle')"))
echo "Successful Insertion!";
else
echo "Please try again";
?>

make sure to watch other video about connecting to the database, to understand include_once(‘db.php’);

Video Tutorial: Insertion of Records into Database: PHP & MySQL


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

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



die function:

1
2
3
4
5
6
7
8
9
< ?php
 
   include_once('db.php');
 
   $res = mysql_query("INSERT INTO apple VALUES('','Oracle')") 
                            or die("sorry, database is busy!");
 
   echo "Successful insertion";
?>

if the insertion operation fails for some reason, the die function is invoked and the message “Sorry, database is busy!” is shown to the use and the script execution halts, and the “Successful insertion” message won’t be echoed.

Data in the database, as shown in the video:
1. Google
2. Apple
3. Microsoft
4. Oracle