0% found this document useful (0 votes)
16 views60 pages

Mongodb

The document discusses MongoDB, a NoSQL database known for its flexibility and scalability in handling unstructured data. It outlines the advantages of NoSQL over traditional SQL databases, describes MongoDB's document model, and provides guidance on creating collections and connecting to the database using Node.js. Additionally, it covers MongoDB's data types, write concerns, and methods for accessing and manipulating databases.

Uploaded by

v647414
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views60 pages

Mongodb

The document discusses MongoDB, a NoSQL database known for its flexibility and scalability in handling unstructured data. It outlines the advantages of NoSQL over traditional SQL databases, describes MongoDB's document model, and provides guidance on creating collections and connecting to the database using Node.js. Additionally, it covers MongoDB's data types, write concerns, and methods for accessing and manipulating databases.

Uploaded by

v647414
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 60

MongoDB(NoSQL)

• At the core of most large-scale web applications and services is a


high-performance data storage solution. The backend data store is
responsible for storing everything from user account information to
shopping cart items to blog and comment data.
• Good web applications must store and retrieve data with accuracy,
speed, and reliability.
• three most common are direct file system storage in files, relational
databases, and NoSQL databases.
• Here chosen data store is MongoDB, which is a NoSQL database.
Why NoSQL?

1. The concept of NoSQL (Not Only SQL) consists of technologies that


provide storage and retrieval without the tightly constrained
models of traditional SQL relational databases.
2. The motivation behind NoSQL is mainly simplified designs,
horizontal scaling, and finer control of the availability of data.
3. NoSQL breaks away from the traditional structure of relational
databases and allows developers to implement models in ways that
more closely fit the data flow needs of their systems.
4. This allows NoSQL databases to be implemented in ways that
traditional relational databases could never be structured.
Here are the four main types of
NoSQL databases:

1. Document databases.
2. Key-value stores.
3. Column-oriented databases.
4. Graph databases.
• NoSQL technologies, such as HBase’s column structure, Redis’s
key/value structure, and Neo4j’s graph structure.
• MongoDB and the document model were chosen because of great
flexibility and scalability when it comes to implementing backend
storage for web applications and services.
• Also MongoDB is one of the most popular and well supported
NoSQL databases currently available.
Differences
• SQL databases are used to store structured data while NoSQL
databases like MongoDB are used to save unstructured data.
• MongoDB is used to save unstructured data in JSON format.
• MongoDB does not support advanced analytics and joins like SQL
databases support.
Understanding MongoDB

• MongoDB is a NoSQL database based on a document model where data


objects are stored as separate documents inside a collection.
• The motivation of the MongoDB language is to implement a data store
that provides high performance, high availability, and automatic scaling.
• MongoDB groups data together through collections.
• A collection is simply a grouping of documents that have the same or a
similar purpose.
• A collection acts similarly to a table in a traditional SQL database, with
one major difference. In MongoDB, a collection is not enforced by a strict
schema;
• A document is a representation of a single entity of data in the
MongoDB database.
• A collection is made up of one or more related objects. A major
difference between MongoDB and SQL is that documents are
different from rows.
• Row data is flat, meaning there is one column for each value in the
row.
• However, in MongoDB, documents can contain embedded
subdocuments, thus providing a much closer inherent data model to
your applications
• In fact, the records in MongoDB that represent documents are
stored as BSON,which is a lightweight binary form of JSON, with
field:value pairs corresponding to JavaScript property:value pairs.
• These field:value pairs define the values stored in the document.
• The maximum size of a document in MongoDB is 16MB, which
prevents queries that result in an excessive amount of RAM being
used or intensive hits to the file system.
MongoDB Data Types

• The BSON data format provides several different types that are used
when storing the JavaScript objects to binary form. These types match
the JavaScript type as closely as possible.
• It is important to understand these types because you can actually
query MongoDB to find objects that have a specific property that has
a value of a certain type.
• MongoDB assigns each of the data types an integer ID number from
1 to 255 that is used when querying by type.
createCollection() Method

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


collection
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 of the collection to be
Name String
created
(Optional) Specify options about
Options Document
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.

autoIndexI (Optional) If true, automatically create index on _id


Boolean
d field.s Default value is false.
(Optional) Specifies a maximum size in bytes for a
size number capped collection. If capped is true, then
you need to specify this field also.
(Optional) Specifies the maximum number of
max number
documents allowed in the capped collection.
• Basic syntax of createCollection() method without options is as
follows
>use test
switched to db test
>db.createCollection("mycollection")
{ "ok" : 1 }
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" } >
• MongoDB To be able to experiment with the code examples, you will
need access to a MongoDB database.
• You can download a free MongoDB database at
https://www.mongodb.com.
• Or get started right away with a MongoDB cloud service at
https://www.mongodb.com/cloud/atlas.
• Install MongoDB Driver
• Let us try to access anode MongoDB database with Node.js.
• To download and install the official MongoDB driver, open the
Command Terminal and execute the following:
• Download and install mongodb package:
• C:\Users\Your Name>npm install mongodb
Install MongoDB Shell (mongosh)
There are many ways to connect to your MongoDB database.
We will start by using the MongoDB Shell, mongosh.
Use the official instructions to install mongosh on your operating system.
To verify that it has been installed properly, open your terminal and type:
mongosh --version
You should see that the latest verion is installed.
The version used in this tutorial is v1.3.1.
• Now you have downloaded and installed a mongodb database driver.
• Node.js can use this module to manipulate MongoDB databases:
• var mongo = require('mongodb');
• Creating a Database
• To create a database in MongoDB, start by creating a MongoClient
object, then specify a connection URL with the correct ip address and
the name of the database you want to create.
• MongoDB will create the database if it does not exist, and make a
connection to it.
Adding the MongoDB Driver to
Node.js
• The first step in implementing MongoDB access from your Node.js applications
is to add the MongoDB driver to your application project. The MongoDB
Node.js driver is the officially supported native Node.js driver for MongoDB.
• adding the MongoDB Node.js driver to your project is a simple npm command.
From your project root directory, execute the following command using a
console prompt:
• npm install mongodb
• A node_modules directory is created if it is not already there, and the
mongodb driver module is installed under it. Once that is done, your Node.js
application files can use the require('mongodb') command to access the
mongodb module functionality.
Connecting to MongoDB from
Node.js
• Once you have installed the mongodb module using the npm
command, you can
• begin accessing MongoDB from your Node.js applications by opening
up a connection to the MongoDB server. The connection acts as your
interface to create, update, and access data in the MongoDB database.
• Accessing MongoDB is best done through the MongoClient class in the
mongodb module. This class provides two main methods to create
connections to MongoDB. One is to create an instance of the
MongoClient object and then use that object to create and manage
the MongoDB connection. The other method uses a connection string
to connect
Understanding the Write Concern
• Before connecting to and updating data on a MongoDB server, you
need to decide what level of write concern you want to implement on
your connection.
• Write concern describes the guarantee that the MongoDB connection
provides when reporting on the success of a write operation.
• A stronger write concern tells MongoDB to wait until the write has
successfully been written to disk completely before responding back,
whereas a weaker write concern may only wait until MongoDB has
successfully scheduled the change to be written before responding
back.
Write concern levels for MongoDB
connections
Connecting to MongoDB from Node.js Using
the
MongoClient Object
• Using a MongoClient object to connect to MongoDB involves creating an
• instance of the client, opening a connection to the
database,authenticating to the database if necessary, and then handling
logout and closure as needed.
• To connect to MongoDB via a MongoClient object, first create an
instance of the MongoClient object using the following syntax:
var client = new MongoClient();
• After you have created the MongoClient, you still need to open a
connection to the MongoDB server database using the connect(url,
options, callback) method. The url is composed of several components
mongodb://[username:password@]host[:port][/[database][?options]]

To connect to a MongoDB database named MyDB on a host named


MyDBServer on port 8088, you would use the following URL:
client.connect('mongodb://MyDBServer:8088/MyDB');
client.connect ('mongodb://MyDBServer:8088/MyDB',
{ connectTimeoutMS: 1000,
reconnectInterval: 500 },
function(err, db){ . . . });
Options used to create the server
object for the MongoClient
• The callback function accepts an error as the first parameter, and a Db
object instance as the second parameter. If an error occurs, the Db
object instance will be null;
• otherwise, you can use it to access the database because the
connection will already be created and authenticated.
• While in the callback function, you can access the MongoDB database
using the Db object passed in as the second parameter.
• When you are finished with the connection, call close() on the Db
object to close the connection
db_connect_url.js: Connecting to
MongoDB using a connection url
db_connect_object.js:
Authenticating using the db object
Understanding the Objects Used
in the
MongoDB Node.js Driver
• Understanding the Db Object
• The Db object inside the MongoDB driver provides access to
databases. It acts as a representation of the database allowing you to
do things like connect, add users, and access collections.
• You use Db objects heavily to gain and maintain access to databases
that you are interacting with in MongoDB. A Db object is typically
created when you connect to the database
Methods on the Db object
• Understanding the Admin Object
• The Admin object is used to perform certain administrative functions
on a MongoDB database. The Admin object represents a connection
specifically to the admin database and provides functionality not
included in the Db object.
• The Admin object can be created using the admin() method on an
instance of the Db object or by passing a Db object into the
constructor. For example, both of the following work fine:
var adminDb = db.admin()
var adminDb = new Admin(db)
Methods on the Admin object
• Understanding the Collection Object
• The Collection object represents a collection in the MongoDB
database. You use the collection object to access items in the
collection, add documents, query documents, and much more.
• A Collection object can be created using the collection() method on an
instance of the Db object or by passing a Db object and collection
name into the constructor. The collection should already be created on
the MongoDB server previously or using the createCollection() method
on the Db object. For example, both of the following work fine:
var collection = db.collection()
var collection = new Collection(db, "myCollection")
db.createCollection("newCollection", function(err, collection){ }
Basic methods on the Collection
object
Understanding the Cursor Object
• When you perform certain operations on MongoDB using the MongoDB
Node.js driver, the results come back as a Cursor object. The Cursor object
acts as a pointer that can be iterated on to access a set of objects in the
database.
• For example, when you use find(), the actual documents are not returned
in the callback function but a Cursor object instead. You can then use the
Cursor object to read the items in the results.
• Because the Cursor object can be iterated on, an index to the current
location is kept internally. That way you can read items one at a time. Keep
in mind that some
• operations only affect the current item in the Cursor and increment the
index. Other operations affect all items at the current index forward.
• In addition to the connection url information, you can also provide an
options object that specifies how the MongoClient object creates and
manages the connection to MongoDB. This options object is the
second parameter to the connect() method.
• the most important settings in the options object that you can set
• when defining the MongoClient object. The callback method is called
back with an error as the first parameter if the connection fails or
with a MongoClient object as the second parameter if the connection
is successful.
Basic methods on the Cursor Object
Accessing and Manipulating
Databases
Listing Databases:
To list the databases in your system, you use the listDatabases() method on
an Admin object. That means that you need to create an instance of an
Admin object first. The list of databases is returned as the second parameter
to the callback function and is a simple array of database objects
Creating a Database
Deleting a Database
• To delete a database from MongoDB, you need to get a Db object
instance that points to that database. Then call the dropDatabase()
method on that object. It may take a while for MongoDB to finalize
the deletion. If you need to verify that the deletion occurred, you can
use a timeout to wait for the database delete to occur.
Getting the Status of the MongoDB
Server
• var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/mydb";

MongoClient.connect(url, function(err, db) {


if (err) throw err;
console.log("Database created!");
db.close();
});
• MongoDB waits until you have created a collection (table), with at
least one document (record) before it actually creates the database
(and collection).
Create Collections
• var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/";

MongoClient.connect(url, function(err, db) {


if (err) throw err;
var dbo = db.db("mydb");
dbo.createCollection("customers", function(err, res) {
if (err) throw err;
console.log("Collection created!");
db.close();
});
});
• var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/";

MongoClient.connect(url, function(err, db) {


if (err) throw err;
var dbo = db.db("mydb");
var myobj = { name: ”lakshmi", address: “GUN126616" };
dbo.collection("customers").insertOne(myobj, function(err, res) {
if (err) throw err;
console.log("1 document inserted");
db.close();
});
});
• var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/";

MongoClient.connect(url, function(err, db) {


if (err) throw err;
var dbo = db.db("mydb");
var myobj = [
{ name: ‘lakshmi', address: ‘GUN15'},
{ name: ‘Rishi', address: 'Lowstreet 4'},
{ name: ‘Babu', address: 'Guntur652'},
{ name: 'Hannah', address: 'Mountain 21'},
{ name: 'Michael', address: 'Valley 345'},
{ name: 'Sandy', address: 'Ocean blvd 2'},
{ name: 'Betty', address: 'Green Grass 1'},
];
dbo.collection("customers").insertMany(myobj, function(err, res) {
if (err) throw err;
console.log("Number of documents inserted: " + res.insertedCount);
db.close();
});
});
• var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/";

MongoClient.connect(url, function(err, db) {


if (err) throw err;
var dbo = db.db("mydb");
dbo.collection("customers").findOne({}, function(err, result) {
if (err) throw err;
console.log(result.name);
db.close();
});
});

You might also like