WD Notes

Download as pdf or txt
Download as pdf or txt
You are on page 1of 79

UNIT-4 WD NOTES

What is Streams?

Streams are objects that let you read data from a source or write data to a
destination in continuous fashion. In Node.js, there are four types of streams −

● Readable − Stream which is used for read operation.


● Writable − Stream which is used for write operation.
● Duplex − Stream which can be used for both read and write operation.
● Transform − A type of duplex stream where the output is computed
based on input.

Each type of Stream is an EventEmitter instance and throws several events at


different instance of times. For example, some of the commonly used events
are −

● data − This event is fired when there is data is available to read.


● end − This event is fired when there is no more data to read.
● error − This event is fired when there is any error receiving or writing
data.
● finish − This event is fired when all the data has been flushed to
underlying system.

Why Streams?

Streams basically provide two major advantages compared to other data

handling methods:

Memory efficiency: you don’t need to load large amounts of data in

memory before you are able to process it


1. Time efficiency: it takes significantly less time to start

processing data as soon as you have it, rather than having to

wait with processing until the entire payload has been

transmitted

Types of Streams

● Writable: streams to which we can write data. For example,


fs.createWriteStream() lets us write data to a file using streams.
● Readable: streams from which data can be read. For example:
fs.createReadStream() lets us read the contents of a file.
● Duplex: streams that are both Readable and Writable. For example,
net.Socket
● Transform: streams that can modify or transform the data as it is
written and read. For example, in the instance of file-compression, you
can write compressed data and read decompressed data to and from
a file.

Streams – Reading a Stream

Create a text file named input.txt having the following content:

1. This is a demonstration of reading from a Stream concepts

Create a JavaScript file named main.js having the following:

File: main.js
1. var fs = require("fs");

2. var data = '';

3. // Create a readable stream

4. var readerStream = fs.createReadStream('input.txt');

5. // Set the encoding to be utf8.

6. readerStream.setEncoding('UTF8');

7. // Handle stream events --> data, end, and error

8. readerStream.on('data', function(chunk) {

9. data += chunk;

10. });

11. readerStream.on('end',function(){

12. console.log(data);

13. });

14. readerStream.on('error', function(err){

15. console.log(err.stack);

16. });

17. console.log("Program Ended");

Now, open the Node.js command prompt and run the main.js

1. node main.js
Node.js Writing to a stream

Create a JavaScript file named main.js having the following code:

File: main.js

1. var fs = require("fs");

2. var data = 'A Solution of all Technology';

3. // Create a writable stream

4. var writerStream = fs.createWriteStream('output.txt');

5. // Write the data to stream with encoding to be utf8

6. writerStream.write(data,'UTF8');

7. // Mark the end of file

8. writerStream.end();

9. // Handle stream events --> finish, and error

10. writerStream.on('finish', function() {

11. console.log("Write completed.");

12. });

13. writerStream.on('error', function(err){

14. console.log(err.stack);

15. });

16. console.log("Program Ended");

Now open the Node.js command prompt and run the main.js

1. node main.js
You will see the following result:

Now, you can see that a text file named "output.txt" is created where you had
saved "input.txt" and "main.js" file. In my case, it is on desktop.

Open the "output.txt" and you will see the following content.

Node.js Piping Streams


Piping is a mechanism where output of one stream is used as input to
another stream. There is no limit on piping operation.

Let's take a piping example for reading from one file and writing it to another
file.

File: main.js

1. var fs = require("fs");

2. // Create a readable stream

3. var readerStream = fs.createReadStream('input.txt');

4. // Create a writable stream

5. var writerStream = fs.createWriteStream('output.txt');

6. // Pipe the read and write operations

7. // read input.txt and write data to output.txt

8. readerStream.pipe(writerStream);

9. console.log("Program Ended");

Open the Node.js and run the mian.js

1. node main.js
Now, you can see that a text file named "output.txt" is created where you had
saved ?main.js? file. In my case, it is on desktop.

Open the "output.txt" and you will see the following content.

Node.js Chaining Streams

Chaining stream is a mechanism of creating a chain of multiple stream


operations by connecting output of one stream to another stream. It is
generally used with the piping operation.

Let's take an example of piping and chaining to compress a file and then
decompress the same file.

File: main.js

1. var fs = require("fs");

2. var zlib = require('zlib');

3. // Compress the file input.txt to input.txt.gz

4. fs.createReadStream('input.txt')

5. .pipe(zlib.createGzip())

6. .pipe(fs.createWriteStream('input.txt.gz'));

7. console.log("File Compressed.");
Open the Node.js command prompt and run main.js

1. node main.js

You will get the following result:

Now you will see that file "input.txt" is compressed and a new file is created
named "input.txt.gz" in the current file.

To Decompress the same file: put the following code in the js file "main.js"

File: main.js

1. var fs = require("fs");

2. var zlib = require('zlib');

3. // Decompress the file input.txt.gz to input.txt

4. fs.createReadStream('input.txt.gz')

5. .pipe(zlib.createGunzip())

6. .pipe(fs.createWriteStream('input.txt'));

7. console.log("File Decompressed.");
Open the Node.js command prompt and run main.js

1. node main.js

Node.js as a File Server

Node implements File I/O using simple wrappers around standard POSIX
functions. The Node File System (fs) module can be imported using the
following syntax −

var fs = require("fs")

Synchronous vs Asynchronous
Every method in the fs module has synchronous as well as asynchronous
forms. Asynchronous methods take the last parameter as the completion
function callback and the first parameter of the callback function as error. It
is better to use an asynchronous method instead of a synchronous method,
as the former never blocks a program during its execution, whereas the
second one does.

Example
Create a text file named input.txt with the following content −

This is a demonstration of Streams in Node.js

Let us create a js file named main.js with the following code −

var fs = require("fs");

// Asynchronous read
fs.readFile('input.txt', function (err, data) {
if (err) {
return console.error(err);
}
console.log("Asynchronous read: " + data.toString());
});

// Synchronous read
var data = fs.readFileSync('input.txt');
console.log("Synchronous read: " + data.toString());

console.log("Program Ended");

Now run the main.js to see the result −

$ node main.js

The following sections provides a set of good examples on major File I/O
methods.

Open a File

Syntax
Following is the syntax of the method to open a file in asynchronous mode −
fs.open(path, flags[, mode], callback)

Parameters
Here is the description of the parameters used −

● path − This is the string having file name including path.


● flags − Flags indicate the behavior of the file to be opened. All possible
values have been mentioned below.
● mode − It sets the file mode (permission and sticky bits), but only if the
file was created. It defaults to 0666, readable and writeable.
● callback − This is the callback function which gets two arguments (err,
fd).

Flags
Flags for read/write operations are −

Sr.No. Flag & Description

1
r

Open file for reading. An exception occurs if the file does not

exist.

2
r+

Open file for reading and writing. An exception occurs if the file

does not exist.


3
rs

Open file for reading in synchronous mode.

4
rs+

Open file for reading and writing, asking the OS to open it

synchronously. See notes for 'rs' about using this with caution.

5
w

Open file for writing. The file is created (if it does not exist) or

truncated (if it exists).

6
wx

Like 'w' but fails if the path exists.

7
w+
Open file for reading and writing. The file is created (if it does

not exist) or truncated (if it exists).

8
wx+

Like 'w+' but fails if path exists.

9
a

Open file for appending. The file is created if it does not exist.

10
ax

Like 'a' but fails if the path exists.

11
a+

Open file for reading and appending. The file is created if it

does not exist.

12
ax+
Like 'a+' but fails if the the path exists.

Example
Let us create a js file named main.js having the following code to open a file
input.txt for reading and writing.

var fs = require("fs");

// Asynchronous - Opening File


console.log("Going to open file!");
fs.open('input.txt', 'r+', function(err, fd) {
if (err) {
return console.error(err);
}
console.log("File opened successfully!");
});

Now run the main.js to see the result −

$ node main.js

Verify the Output.

Going to open file!


File opened successfully!

Get File Information

Syntax
Following is the syntax of the method to get the information about a file −

fs.stat(path, callback)
Parameters
Here is the description of the parameters used −

● path − This is the string having file name including path.


● callback − This is the callback function which gets two arguments (err,
stats) where stats is an object of fs.Stats type which is printed below in
the example.

Apart from the important attributes which are printed below in the example,
there are several useful methods available in fs.Stats class which can be
used to check file type. These methods are given in the following table.

Sr.No. Method & Description

1
stats.isFile()

Returns true if file type of a simple file.

2
stats.isDirectory()

Returns true if file type of a directory.

3
stats.isBlockDevice()

Returns true if file type of a block device.


4
stats.isCharacterDevice()

Returns true if file type of a character device.

5
stats.isSymbolicLink()

Returns true if file type of a symbolic link.

6
stats.isFIFO()

Returns true if file type of a FIFO.

7
stats.isSocket()

Returns true if file type of asocket.

Example
Let us create a js file named main.js with the following code −

var fs = require("fs");

console.log("Going to get file info!");


fs.stat('input.txt', function (err, stats) {
if (err) {
return console.error(err);
}
console.log(stats);
console.log("Got file info successfully!");

// Check file type


console.log("isFile ? " + stats.isFile());
console.log("isDirectory ? " + stats.isDirectory());
});

Now run the main.js to see the result −

$ node main.js

Verify the Output.

Going to get file info!


{
dev: 1792,
mode: 33188,
nlink: 1,
uid: 48,
gid: 48,
rdev: 0,
blksize: 4096,
ino: 4318127,
size: 97,
blocks: 8,
atime: Sun Mar 22 2015 13:40:00 GMT-0500 (CDT),
mtime: Sun Mar 22 2015 13:40:57 GMT-0500 (CDT),
ctime: Sun Mar 22 2015 13:40:57 GMT-0500 (CDT)
}
Got file info successfully!
isFile ? true
isDirectory ? false

Writing a File

Syntax
Following is the syntax of one of the methods to write into a file −

fs.writeFile(filename, data[, options], callback)

This method will over-write the file if the file already exists. If you want to write
into an existing file then you should use another method available.

Parameters
Here is the description of the parameters used −

● path − This is the string having the file name including path.
● data − This is the String or Buffer to be written into the file.
● options − The third parameter is an object which will hold {encoding,
mode, flag}. By default. encoding is utf8, mode is octal value 0666. and
flag is 'w'
● callback − This is the callback function which gets a single parameter
err that returns an error in case of any writing error.

Example
Let us create a js file named main.js having the following code −

var fs = require("fs");

console.log("Going to write into existing file");


fs.writeFile('input.txt', 'Simply Easy Learning!', function(err) {
if (err) {
return console.error(err);
}

console.log("Data written successfully!");


console.log("Let's read newly written data");

fs.readFile('input.txt', function (err, data) {


if (err) {
return console.error(err);
}
console.log("Asynchronous read: " + data.toString());
});
});

Now run the main.js to see the result −

$ node main.js

Verify the Output.

Going to write into existing file


Data written successfully!
Let's read newly written data
Asynchronous read: Simply Easy Learning!

Reading a File

Syntax
Following is the syntax of one of the methods to read from a file −

fs.read(fd, buffer, offset, length, position, callback)

This method will use file descriptor to read the file. If you want to read the file
directly using the file name, then you should use another method available.

Parameters
Here is the description of the parameters used −

● fd − This is the file descriptor returned by fs.open().


● buffer − This is the buffer that the data will be written to.
● offset − This is the offset in the buffer to start writing at.
● length − This is an integer specifying the number of bytes to read.
● position − This is an integer specifying where to begin reading from in
the file. If position is null, data will be read from the current file position.
● callback − This is the callback function which gets the three arguments,
(err, bytesRead, buffer).
Example
Let us create a js file named main.js with the following code −

var fs = require("fs");
var buf = new Buffer(1024);

console.log("Going to open an existing file");


fs.open('input.txt', 'r+', function(err, fd) {
if (err) {
return console.error(err);
}
console.log("File opened successfully!");
console.log("Going to read the file");

fs.read(fd, buf, 0, buf.length, 0, function(err, bytes){


if (err){
console.log(err);
}
console.log(bytes + " bytes read");

// Print only read bytes to avoid junk.


if(bytes > 0){
console.log(buf.slice(0, bytes).toString());
}
});
});

Now run the main.js to see the result −

$ node main.js

Verify the Output.

Going to open an existing file


File opened successfully!
Going to read the file
97 bytes read
Tutorials Point is giving self learning content
to teach the world in simple and easy way!!!!!

Closing a File

Syntax
Following is the syntax to close an opened file −

fs.close(fd, callback)

Parameters
Here is the description of the parameters used −

● fd − This is the file descriptor returned by file fs.open() method.


● callback − This is the callback function No arguments other than a
possible exception are given to the completion callback.

Example
Let us create a js file named main.js having the following code −

var fs = require("fs");
var buf = new Buffer(1024);

console.log("Going to open an existing file");


fs.open('input.txt', 'r+', function(err, fd) {
if (err) {
return console.error(err);
}
console.log("File opened successfully!");
console.log("Going to read the file");

fs.read(fd, buf, 0, buf.length, 0, function(err, bytes) {


if (err) {
console.log(err);
}
// Print only read bytes to avoid junk.
if(bytes > 0) {
console.log(buf.slice(0, bytes).toString());
}

// Close the opened file.


fs.close(fd, function(err) {
if (err) {
console.log(err);
}
console.log("File closed successfully.");
});
});
});

Now run the main.js to see the result −

$ node main.js

Verify the Output.

Going to open an existing file


File opened successfully!
Going to read the file
Tutorials Point is giving self learning content
to teach the world in simple and easy way!!!!!

File closed successfully.

Truncate a File

Syntax
Following is the syntax of the method to truncate an opened file −

fs.ftruncate(fd, len, callback)


Parameters
Here is the description of the parameters used −

● fd − This is the file descriptor returned by fs.open().


● len − This is the length of the file after which the file will be truncated.
● callback − This is the callback function No arguments other than a
possible exception are given to the completion callback.

Example
Let us create a js file named main.js having the following code −

var fs = require("fs");
var buf = new Buffer(1024);

console.log("Going to open an existing file");


fs.open('input.txt', 'r+', function(err, fd) {
if (err) {
return console.error(err);
}
console.log("File opened successfully!");
console.log("Going to truncate the file after 10 bytes");

// Truncate the opened file.


fs.ftruncate(fd, 10, function(err) {
if (err) {
console.log(err);
}
console.log("File truncated successfully.");
console.log("Going to read the same file");

fs.read(fd, buf, 0, buf.length, 0, function(err, bytes){


if (err) {
console.log(err);
}

// Print only read bytes to avoid junk.


if(bytes > 0) {
console.log(buf.slice(0, bytes).toString());
}

// Close the opened file.


fs.close(fd, function(err) {
if (err) {
console.log(err);
}
console.log("File closed successfully.");
});
});
});
});

Now run the main.js to see the result −

$ node main.js

Verify the Output.

Going to open an existing file


File opened successfully!
Going to truncate the file after 10 bytes
File truncated successfully.
Going to read the same file
Tutorials
File closed successfully.

Delete a File

Syntax
Following is the syntax of the method to delete a file −

fs.unlink(path, callback)

Parameters
Here is the description of the parameters used −

● path − This is the file name including path.


● callback − This is the callback function No arguments other than a
possible exception are given to the completion callback.

Example
Let us create a js file named main.js having the following code −

var fs = require("fs");

console.log("Going to delete an existing file");


fs.unlink('input.txt', function(err) {
if (err) {
return console.error(err);
}
console.log("File deleted successfully!");
});

Create Files, Reading Files


Delete Files

Creating a Upload Form

The Formidable Module

There is a very good module for working with file uploads, called "Formidable".

The Formidable module can be downloaded and installed using NPM:

C:\Users\Your Name>npm install formidable

After you have downloaded the Formidable module, you can include the module
in any application:
var formidable = require('formidable');

Upload Files

Now you are ready to make a web page in Node.js that lets the user upload files
to your computer:

Step 1: Create an Upload Form

Create a Node.js file that writes an HTML form, with an upload field:

Example

This code will produce an HTML form:

var http = require('http');

http.createServer(function (req, res) {

res.writeHead(200, {'Content-Type': 'text/html'});

res.write('<form action="fileupload" method="post" enctype="multipart/form-data">');

res.write('<input type="file" name="filetoupload"><br>');

res.write('<input type="submit">');

res.write('</form>');

return res.end();

}).listen(8080);
Step 2: Parse the Uploaded File

Include the Formidable module to be able to parse the uploaded file once it
reaches the server.

When the file is uploaded and parsed, it gets placed on a temporary folder on
your computer.

Example

The file will be uploaded, and placed on a temporary folder:

var http = require('http');

var formidable = require('formidable');

http.createServer(function (req, res) {

if (req.url == '/fileupload') {

var form = new formidable.IncomingForm();

form.parse(req, function (err, fields, files) {

res.write('File uploaded');

res.end();

});

} else {

res.writeHead(200, {'Content-Type': 'text/html'});


res.write('<form action="fileupload" method="post"
enctype="multipart/form-data">');

res.write('<input type="file" name="filetoupload"><br>');

res.write('<input type="submit">');

res.write('</form>');

return res.end();

}).listen(8080);

Step 3: Save the File

When a file is successfully uploaded to the server, it is placed on a temporary


folder.

The path to this directory can be found in the "files" object, passed as the third
argument in the parse() method's callback function.

To move the file to the folder of your choice, use the File System module, and
rename the file:

Example

Include the fs module, and move the file to the current folder:

var http = require('http');

var formidable = require('formidable');

var fs = require('fs');
http.createServer(function (req, res) {

if (req.url == '/fileupload') {

var form = new formidable.IncomingForm();

form.parse(req, function (err, fields, files) {

var oldpath = files.filetoupload.path;

var newpath = 'C:/Users/Your Name/' + files.filetoupload.name;

fs.rename(oldpath, newpath, function (err) {

if (err) throw err;

res.write('File uploaded and moved!');

res.end();

});

});

} else {

res.writeHead(200, {'Content-Type': 'text/html'});

res.write('<form action="fileupload" method="post"


enctype="multipart/form-data">');

res.write('<input type="file" name="filetoupload"><br>');

res.write('<input type="submit">');
res.write('</form>');

return res.end();

}).listen(8080);

Nodemailer Modules

The Nodemailer module makes it easy to send emails from your computer.

The Nodemailer module can be downloaded and installed using npm:

C:\Users\Your Name>npm install nodemailer

After you have downloaded the Nodemailer module, you can include the module
in any application:

var nodemailer = require('nodemailer');

Send an Email

Now you are ready to send emails from your server.

Use the username and password from your selected email provider to send an
email. This tutorial will show you how to use your Gmail account to send an email:

Example

var nodemailer = require('nodemailer');


var transporter = nodemailer.createTransport({

service: 'gmail',

auth: {

user: 'youremail@gmail.com',

pass: 'yourpassword'

});

var mailOptions = {

from: 'youremail@gmail.com',

to: 'myfriend@yahoo.com',

subject: 'Sending Email using Node.js',

text: 'That was easy!'

};

transporter.sendMail(mailOptions, function(error, info){

if (error) {

console.log(error);
} else {

console.log('Email sent: ' + info.response);

});

And that's it! Now your server is able to send emails.

Multiple Receivers

To send an email to more than one receiver, add them to the "to" property of the
mailOptions object, separated by commas:

Example

Send email to more than one address:

var mailOptions = {

from: 'youremail@gmail.com',

to: 'myfriend@yahoo.com, myotherfriend@yahoo.com',

subject: 'Sending Email using Node.js',

text: 'That was easy!'

Send HTML

To send HTML formatted text in your email, use the "html" property instead of the
"text" property:
ExampleSend email containing HTML:

var mailOptions = {

from: 'youremail@gmail.com',

to: 'myfriend@yahoo.com',

subject: 'Sending Email using Node.js',

html: '<h1>Welcome</h1><p>That was easy!</p>'

Mongo DB

Introduction:

MongoDB is a NoSQL database. There are different types of NoSQL


databases, so to be specific MongoDB is an open source document
based NoSQL database
Mongodb Datatypes:
i)Integer ii)Boolean iii)Double
iv)String v)Arrays vi)Object vii)Null
viii)Regular expression ix)Timestamp x)Date
xi)Object ID

History of MongoDB
MongoDB was created by Eliot and Dwight (founders of DoubleClick) in
2007, when they faced scalability issues while working with relational
database. The organization that developed MongoDB was originally
known as 10gen.

In Feb 2009, they changed their business model and released MongoDB
as an open source Project. The organization changed its name in 2013
and now known as MongoDB Inc.

Features of MongDB

Mapping Relational Database to MongoDB


Collections
in MongoDB is equivalent to the tables in RDBMS.

Documents in MongoDB is equivalent to the rows in RDBMS.

Fields in MongoDB is equivalent to the columns in RDBMS.

This is how a document looks in MongoDB: As you can see this is similar
to the row in RDBMS. The only difference is that they are in JSON format.

Mongo DB Datatypes
In MongoDB, the documents are stores in BSON, which is the binary
encoded format of JSON and using BSON we can make remote
procedure calls in MongoDB. BSON data format supports various
data-types. Below are the enlisted MongoDB data types:

1. String: This is the most commonly used data type in MongoDB to store
data, BSON strings are of UTF-8. So, the drivers for each programming
language convert from the string format of the language to UTF-8 while
serializing and de-serializing BSON. The string must be a valid UTF-8.

Example: In the following example we are storing the name of the


student in the student collection:

Here, the data type of the value of the name field is a string.

2. Integer: In MongoDB, the integer data type is used to store an integer


value. We can store integer data type in two forms 32 -bit signed
integer and 64 – bit signed integer.

Example: In the following example we are storing the age of the student
in the student collection:
3. Double: The double data type is used to store the floating-point
values.

Example: In the following example we are storing the marks of the


student in the student collection:
4. Boolean: The boolean data type is used to store either true or false.

Example: In the following example we are storing the final result of the
student as pass or fail in boolean values.

5. Null: The null data type is used to store the null value.

Example: In the following example, the student does not have a mobile
number so the number field contains the value null.
6. Array: The Array is the set of values. It can store the same or different
data types values in it. In MongoDB, the array is created using square
brackets([]).

Example: In the following example, we are storing the technical skills of


the student as an array.
7. Object: Object data type stores embedded documents. Embedded
documents are also known as nested documents. Embedded
document or nested documents are those types of documents which
contain a document inside another document.

Example: In the following example, we are storing all the information


about a book in an embedded document.
8. Object Id: Whenever we create a new document in the collection
MongoDB automatically creates a unique object id for that document(if
the document does not have it). There is an _id field in MongoDB for
each document. The data which is stored in Id is of hexadecimal format
and the length of the id is 12 bytes which consist:

● 4-bytes for Timestamp value.

● 5-bytes for Random values. i.e., 3-bytes for machine Id and

2-bytes for process Id.

● 3- bytes for Counter

You can also create your own id field, but make sure that the value of
that id field must be unique.
Example: In the following example, when we insert a new document it
creates a new unique object id for it.

9. Undefined: This data type stores the undefined values.

Example: In the following example the type of the duration of the project
is undefined.

10. Binary Data: This datatype is used to store binary data.

Example: In the following example the value stored in the binaryValue


field is of binary type.
11. Date: Date data type stores date. It is a 64-bit integer which
represents the number of milliseconds. BSON data type generally
supports UTC datetime and it is signed. If the value of the date data
type is negative then it represents the dates before 1970. There are
various methods to return date, it can be returned either as a string or
as a date object. Some method for the date:

● Date(): It returns the current date in string format.

● new Date(): Returns a date object. Uses the ISODate() wrapper.

● new ISODate(): It also returns a date object. Uses the ISODate()

wrapper.

Example: In the following example we are using all the above method of
the date:
12. Min & Max key: Min key compares the value of the lowest BSON
element and Max key compares the value against the highest BSON
element. Both are internal data types.

Example:

13. Symbol: This data type similar to the string data type. It is generally
not supported by a mongo shell, but if the shell gets a symbol from the
database, then it converts this type into a string type.

Example:
14. Regular Expression: This datatype is used to store regular
expressions.

Example: In the following example we are storing the regular expression


gfg:

15. JavaScript: This datatype is used to store JavaScript code into the
document without the scope.

Example: In this example, we are using the JavaScript syntax in the shell:
16. JavaScript with Scope: This MongoDB data type store JavaScript
data with a scope.

Example: In this example, we are using the JavaScript syntax in the shell:

17. Timestamp: In MongoDB, this data type is used to store a timestamp.


It is useful when we modify our data to keep a record and the value of
this data type is 64-bit. The value of the timestamp data type is always
unique.
Example:

Installing and Working with MongoDB interfaces:


i)Mongo Shell,

MongoDB Mongo shell features

MongoDB Mongo shell is the default client for the MongoDB database
server. It’s a command-line interface (CLI), where the input and
output are all console-based. The Mongo shell is a good tool to
manipulate small sets of data.

Here are the top features that Mongo shell offers:

​ Run all MongoDB queries from the Mongo shell.


​ Manipulate data and perform administration operations.
​ Mongo shell uses JavaScript and a related API to issue
commands.
​ See previous commands in the mongo shell with up and
down arrow keys.
​ View possible command completions using the tab
button after partially entering a command.
​ Print error messages, so you know what went wrong with
your commands.

MongoDB has recently introduced a new mongo shell known as


mongosh. It has some additional features, such as extensibility and
embeddability—that is, the ability to use it inside other products such
as VS Code.

Installing the mongo shell

The mongo shell gets installed when you install the MongoDB server.
It is installed in the same location as the MongoDB server binary.

If you want to install it separately, you can visit the MongoDB


download center, from there select the version and package you
need, download the archive, and copy it to a location in your file
system.

Mongo shell is available for all main operating systems, including:

​ Windows
​ Linux
​ Mac OS

Connect to MongoDB database

Once you’ve downloaded and installed MongoDB, you can use the
mongo shell to connect with a MongoDB server that is up and
running.

Note: It is required that your server is already running before you


connect with it through the shell. You can start the server in CMD
using the following command.

Copy
net start MongoDB

Then type mongo command to run the shell.

Copy
Mongo
Now you are in the Mongo shell.

If you want, you can run the mongo and mongod without the
command prompt. To do this, go to the installation location and
double click on the mongod and mongo applications. You will get the
same result as the above.

Different port

The above mongo command only works if your MongoDB server runs
on the default port, which is 27017. If your MongoDB server runs on a
different port, you have to explicitly specify it in the command, as
shown below:

Copy
mongo --port 28010

Remote server

Both of the above commands only work if your MongoDB server is


running on the localhost. If you want to connect to a remote server,
use the `–host` option with the mongo command, as shown below.
Copy
mongo --host mongodb0.example.com --port 28010

Basic commands for Mongo shell

Now it’s time to work with the Mongo shell. First, we will learn some
basic commands that will help you to get started with using
MongoDB.

Run the db command to see the database you are currently working
with

Copy
db

Run the use command to switch to a different database. If you don’t


have a database, learn how to create a new database.

Copy
use company

You can create collections and insert data with the following
command:
​ db refers to the current database in use.
​ employee is the collection name.
​ insertOne is the method to insert a document to the
collection.

Copy
db.employee.insertOne( { name: "mark" } );

Use the find method to fetch data in a collection. The


forEach(printjson) method will print them with JSON formatting

Copy
db.employee.find().forEach(printjson)

Use the show dbs command to Show all databases

Copy
show dbs
One important command will help you work with the Mongo shell
easily: the help command. Run the help command to get a list of
help options available in the mongo shell.

Copy
Help

To get a full list of commands that you can execute on the current
database, type db.help()
Disadvantages of the mongo shell

Although the Mongo shell is an excellent tool for learning and testing
the MongoDB server, it is difficult to be used in a production
environment. Being a shell inherently carries certain disadvantages.
They are:

​ The Mongo shell is strictly a console centric method of


data manipulation. While some find it easy and quick,
others might not find those characteristics appealing.
​ If you are working on multiple sessions, you need multiple
terminals.
​ If the results are too long, they scroll away.
​ Repetitive commands or debugging a function need the
programmer to traverse the long command line history
manually.
ii)Mongo Compass

MongoDB Compass is a GUI for MongoDB. It is also known as MongoDB GUI.


MongoDB allows users to analyze the content of their stored data without any
prior knowledge of MongoDB query syntax. When we explore exploring our
data in the visual environment, we can use Compass GUI to optimize
performance, manage indexes, and implement document-validation.

All the versions of MongoDB Compass are opensource (i.e., we can freely
deploy and view the repositories of all MongoDB GUI versions).

Step 1: To download MongoDB Compass, you can use your preferred web
browser, and Open the
https://www.mongodb.com/download-center/compass?jmp=docs page.

Step 2: You need to select the installer and version you prefer. GUI installer are
available as a .exe or .msi package or a .zip archive.

Step 3: Finally, Click on the download button.


Step 4: Click on the installer file after the download is complete.

Step 5: Follow the pop-ups to install MongoDB Compass GUI.

Step 6: Once it is installed, it launches and ask you to configure privacy


settings and specify update preference.

Establishing connection with MongoDB Compass.

There are two methods to connect our deployment in MongoDB compass,


either we can use the connection string provided on the MongoDB Atlas or we
can fill our deployment information in specified fields.

By Pasting Connection String.

Step 1: When you log in to Compass, an initial dialogue will appear.

Step 2: To get the deployment connection string for an Atlas cluster, go to


your Atlas cluster view.

Step 3: Click Connect for the cluster you want to connect.


Step 4: After that, click Connect with MongoDB Compass and copy the
provided connection string.
Step 5: Click on connect button, to connect and navigate to the Compass GUI
Home Page.

The Compass Home screen displays the details about the MongoDB instance
from which Compass is connected, which includes the connection name, the
deployment type, hostname, and port, version of MongoDB, performance
statistics, and a list of the instance's databases.

Creating and Managing Database using Compass

When you are connected to the MongoDB Atlas or Mongo Shell, the following
window will appear. Inside this window, you can see the Database tab. The
Database window shows the lists of all the existing databases for your
MongoDB deployment.
On the above window, when you select a database from the given list to view
its collections. You can view database collection when you click the desired
Database in the left navigation pan.

Create a Database in Compass

Step 1: Click on the Create Database button from the database tab. It will take
you to the Create Database pop-up dialogue.
Step 2: In the appeared pop-up window, fill the Database and collection
name to create a new database.
Step 3: Finally, click on Create Database button to create the Database and
collection.
Drop a Database in Compass

Step 1: Click on the trash icon that will appear when you hover over the
Database name, after that a confirmation dialog appears.
Step 2: In the pop-up window, enter the name of the Database that you want
to delete.
Step 3: Finally, click Drop Database button to delete the Database you
selected.
Collections in MongoDB Compass

The Collection window displays the list of all the existing collection and views
from the database you have selected. It includes all the name and other
related information for the selected collection or view.

If you want to gain access to the collection of a database, click on the


Database Name in the main Database view, or Click on the database in the
left navigation pan.
The collection window displays the information like - Collection name,
number of documents, size, number of indexes, size of indexes, and Collation
properties for the collection.

Create a Collection in MongoDB Compass

Step 1: Click on the Create Collection button.


Step 2: After that, fill in the collection details in the Create Collection dialog.

Step 3: Now, click on Create Collection to create the collection


Drop a Collection

Step 1: In the collection window, click on the bin icon for the collection to
delete. When you click on the trash icon, a dialog appears to ask your
confirmation.
Step 2: In the appeared pop-up dialogue, enter the name of the collection you
want to delete from the database.

Step 3: Finally, click on Drop Collection button to delete the collection.


Managing Documents in MongoDB Compass

Documents are the records in a MongoDB collection. Documents are the


basic unit of data in MongoDB. Using the document tab, we can perform the
following tasks in our selected collection or view:

● View the documents: The Document tab provides three ways to access

document in MongoDB Compass.

○ List View - It is the default view of the Database in the MongoDB

Compass. Document will be shown as individual members of the

list. In the list view you can easily extend the embedded objects

and arrays.
○ JSON View - In this view documents will be shown as

completely-formatted JSON objects. In this view, MongoDB

Compass use extended JSON to display the data-types of field

where the correct data types are used.

○ Table View - The table view display documents as a table row.

The document fields are shown as a column in the table. When

we use table view, we can easily find out the documents that

contains specific field values.

● We can use View buttons to select which view we want to use:

● Insert the document: We can have two ways to insert documents into

our collections:
○ JSON Mode: It allows you to write or paste JSON documents in the

editor. You can use this mode to insert one or many documents

at once as an array in the database.

○ Field-by-Field editor: You can create documents in more

interactive way using this editor. It allows you to select all the field

values and types. It supports only the insertion of a single

document at a time.

● Modify the document: You can update existing document in your

collection. When you make changes to your document, the MongoDB

Compass performs a findAndModify operation to update the existing

document.

● Clone the documents: You can insert new files and documents by

cloning (i.e. by making an exact same copy of the document). You can

copy the schema and values of an existing document/files in a

collection.

● Delete the documents: We can delete the document/file depending of

the tab whether we are viewing our documents in List, JSON, or Table

view.
Introduction to entities of MongoDB:

createDatabase()

The use Command


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.

Syntax
Basic syntax of use DATABASE statement is as follows −

use DATABASE_NAME

Example
If you want to use a database with name <mydb>, then use DATABASE
statement would be as follows −

>use mydb
switched to db mydb

To check your currently selected database, use the command db

>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":"tutorials point"})
>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.

The dropDatabase() Method


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

Syntax
Basic syntax of dropDatabase() command is as follows −

db.dropDatabase()

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

Example
First, check the list of available databases by using the command, show dbs.

>show dbs
local 0.78125GB
mydb 0.23012GB
test 0.23012GB
>

If you want to delete new database <mydb>, then dropDatabase()


command would be as follows −

>use mydb
switched to db mydb
>db.dropDatabase()
>{ "dropped" : "mydb", "ok" : 1 }
>

Now check list of databases.

>show dbs
local 0.78125GB
test 0.23012GB

Collections:
i)createCollection() method with example

The createCollection() Method


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

Syntax
Basic syntax of createCollection() command is as follows −

db.createCollection(name, options)

In the command, name is name of collection to be created. Options is a


document and is used to specify configuration of collection.

Parameter Type Description

Name String Name of the

collection to be

created
Options Document (Optional) Specify

options about

memory size and

indexing

Options parameter is optional, so you need to specify only the name of the
collection. Following is the list of options you can use −

Field Type Description

(Optional) If true, enables a capped

collection. Capped collection is a fixed

size collection that automatically

capped Boolean overwrites its oldest entries when it

reaches its maximum size. If you specify

true, you need to specify size parameter

also.

(Optional) If true, automatically create


autoIndexId Boolean
index on _id field.s Default value is false.

size number (Optional) Specifies a maximum size in

bytes for a capped collection. If capped


is true, then you need to specify this field

also.

(Optional) Specifies the maximum

max number number of documents allowed in the

capped collection.

While inserting the document, MongoDB first checks size field of capped
collection, then it checks max field.

Examples
Basic syntax of createCollection() method without options is as follows −

>use test
switched to db test
>db.createCollection("mycollection")
{ "ok" : 1 }
>

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

>show collections
mycollection
system.indexes

The following example shows the syntax of createCollection() method with


few important options −

> db.createCollection("mycol", { capped : true, autoIndexID : true, size : 6142800,


max : 10000 } ){
"ok" : 0,
"errmsg" : "BSON field 'create.autoIndexID' is an unknown field.",
"code" : 40415,
"codeName" : "Location40415"
}
>

In MongoDB, you don't need to create collection. MongoDB creates collection


automatically, when you insert some document.

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

dropCollection() method with example

The drop() Method


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

Syntax
Basic syntax of drop() command is as follows −

db.COLLECTION_NAME.drop()

Example
First, check the available collections into your database mydb.

>use mydb
switched to db mydb
>show collections
mycol
mycollection
system.indexes
tutorialspoint
>

Now drop the collection with the name mycollection.

>db.mycollection.drop()
true
>

Again check the list of collections into database.

>show collections
mycol
system.indexes
tutorialspoint
>

drop() method will return true, if the selected collection is dropped


successfully, otherwise it will return false.

You might also like