0% found this document useful (0 votes)
13 views58 pages

Mongo

The document provides an overview of NoSQL database types, focusing on graph databases, column family databases, and document-oriented databases like MongoDB. It highlights key features of MongoDB, including high performance, high availability, horizontal scalability, and support for multiple storage engines, while also explaining CRUD operations and how to connect to MongoDB deployments. Additionally, it discusses the document data model, collections, and various query capabilities within MongoDB.

Uploaded by

Aditya
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)
13 views58 pages

Mongo

The document provides an overview of NoSQL database types, focusing on graph databases, column family databases, and document-oriented databases like MongoDB. It highlights key features of MongoDB, including high performance, high availability, horizontal scalability, and support for multiple storage engines, while also explaining CRUD operations and how to connect to MongoDB deployments. Additionally, it discusses the document data model, collections, and various query capabilities within MongoDB.

Uploaded by

Aditya
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/ 58

NoSQL Types

Graph database

Document-oriented

Column family
Graph Database

A typical NoSQL graph database comprises four essential


components: nodes, edges, properties, and labels.
1. Nodes are the basic unit of data in a graph database. They
can represent anything—a person, an organization, a product,
or even a transaction.
2. Edges are the lines that connect nodes, representing the
graph relationships between them.
3. Properties are the attributes of nodes and edges.
4. Labels are used to categorize nodes and edges.
Graph Database

• Social media networks


• eCommerce platforms
• Location-based services
• Fraud Detection
Column family
A column family database is a database object that stores
columns of related data.
Column families
Wide-column are alsodon’t
databases calledhave
widea column databases.
defined table schema, which leaves them
flexible to have certain columns only apply
to certain records.
• Log data
• IoT (Internet of Things) sensor data
• Time-series data, such as temperature
monitoring or financial trading data
• Attribute-based data, such as user
preferences or equipment features
• Real-time analytics
MongoDB is a document database designed for ease of application
development and scaling.
NoSQL database
• non-adherence to the widely used relational database systems
• highly optimized for retrieve and append operations
It uses BSON format
• BSON stands for Binary Javascript Object Notation. It is a bin­ary-
en­coded seri­al­iz­a­tion of JSON documents.
• BSON has been extended to add some optional non-JSON-native
data types, like dates and binary data.
Key Features
High Performance
• MongoDB provides high performance data persistence. In
particular, Support for embedded data models reduces I/O
activity on database system.
• Indexes support faster queries and can include keys from
embedded documents and arrays.
Query API
• The MongoDB Query API supports read and write operations
(CRUD) as well as:
• Data Aggregation
• Text Search and Geospatial Queries.
Key Features
High Availability
MongoDB's replication facility, called replica set, provides:
• automatic failover
• data redundancy.
A replica set is a group of MongoDB servers that maintain the
same data set, providing redundancy and increasing data
availability.
Key Features
Horizontal Scalability
• MongoDB provides horizontal scalability
as part of its core functionality:
• Sharding distributes data across a
cluster of machines.
• MongoDB supports creating zones of
data based on the shard key.
• In a balanced cluster, MongoDB directs
reads and writes covered by a zone only
to those shards inside the zone.
Key Features
Support for Multiple Storage Engines
• MongoDB supports multiple storage engines:
• WiredTiger Storage Engine (including support for Encryption
at Rest)
• In-Memory Storage Engine.
• In addition, MongoDB provides pluggable storage engine API
that allows third parties to develop storage engines for
MongoDB.
BASE Properties
• If ACID properties belong to RDBMSs, BASE properties belong to
NoSQL databases.
• In particular, BASE stands for:
• Basically, Available: The system works all the time
(available in case of failure).
• Soft State: The data source does not have to be consistent
all the time.
• Eventually Consistent: Not immediately consistent, but at
some point, data will be consistent—no guarantee about
when this will occur.
BASE properties are preferred in systems where the ACID model is
CAP Theorem/Properties
Intelligent Operational Data Platform

MongoDB is designed to meet the demands of modern apps with a


technology foundation that enables you through:
1. The document data model – presenting you the best way to
work with data.
2. A distributed systems design – allowing you to intelligently put
data where you want it.
3. A unified experience that gives you the freedom to run
anywhere – allowing you to future-proof your work and eliminate
vendor lock-in.
With these capabilities, you can build an Intelligent Operational
Data Platform, underpinned by MongoDB.
Intelligent Operational Data Platform

Best way to work with data


• Easy: Work with data in a natural, intuitive way
• Fast: Get great performance without a lot of work
• Flexible: Adapt and make changes quickly
• Versatile: Supports a wide variety of data and queries
Intelligent Operational Data Platform

Put data where you need it


• Availability: Deliver globally resilient apps
through sophisticated replication and self-
healing recovery
• Scalability: Grow horizontally through
native sharding
• Workload Isolation: Run operational and
analytical workloads in the same cluster
• Locality: Place data on specific devices
and in specific geographies for governance,
class of service, and low-latency access
Intelligent Operational Data Platform

Freedom to run anywhere


• Portability: Database that runs the same
everywhere
• Cloud Agnostic: Leverage the benefits of
a multi-cloud strategy with no lock-in
• Global coverage: Available as a service in
50+ regions across the major public cloud
providers
MongoDB Shell (mongosh)
• The MongoDB Shell, mongosh, is a fully functional JavaScript and
Node.js 16.x REPL environment for interacting with MongoDB
deployments.
• mongosh is available as a standalone package in the MongoDB
Download Center.
• https://www.mongodb.com/try/download/shell
• To use the MongoDB Shell, you must have a MongoDB deployment
to connect to.
• Atlas - cloud-hosted deployment
• Enterprise/Community Server - local MongoDB deployment
Connect to a Deployment

Connect to a Local Deployment on the Default Port


• To connect to a MongoDB deployment running on localhost with
default port 27017, run mongosh without any options:
mongosh
• This is equivalent to the following command:
mongosh "mongodb://localhost:27017"
Connect to a Deployment

Connect to a Local Deployment on a Non-Default Port


• To specify a port to connect to on localhost, you can use either:
• A connection string with the chosen port
• The --port command-line option
• For example, the following commands connect to a deployment
running on localhost port 28015:
mongosh "mongodb://localhost:28015"
mongosh --port 28015
Connect to a Deployment

Connect to a Deployment on a Remote Host


• To specify a remote host and port, you can use either:
• A connection string with the chosen host and port.
• The --host and --port command-line options. If you omit the --
port option, mongosh uses the default port 27017.
• For example, the following commands connect to a MongoDB
deployment running on host mongodb0.example.com and port
28015:
mongosh "mongodb://mongodb0.example.com:28015"
mongosh --host mongodb0.example.com --port 28015
Databases and Collections

MongoDB stores data records as documents (specifically


BSON documents) which are gathered together in
collections.
A database stores one or more collections of documents.
Databases and Collections
Collections
MongoDB stores documents in collections. Collections are analogous
to tables in relational databases.
Databases and Collections
Document Database
• A record in MongoDB is a document, which is a data structure
composed of field and value pairs.
• MongoDB documents are similar to JSON objects.
• The values of fields may include other documents, arrays, and
arrays of documents.
Databases and Collections

Databases
In MongoDB, databases hold one or more collections of documents.
To select a database to use, in mongosh, issue the use <db>
statement, as in the following example:
use myDB
If you want to check your databases list, use the command show
dbs.
>show dbs
Databases and Collections

Explicit Creation
MongoDB provides the db.createCollection() method to explicitly
create a collection with various options, such as setting the
maximum size or the documentation validation rules.
If you are not specifying these options, you do not need to explicitly
create the collection since MongoDB creates new collections when
you first store data for the collections.
db.createCollection(name, options)

If you want to check your Collections list, use the command show
collections.
>show collections
Databases and Collections

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.
Databases and Collections

Create a Collection
If a collection does not exist, MongoDB creates the collection when
you first store data for that collection.
db.myNewCollection2.insertOne( { x: 1 } )
db.myNewCollection3.createIndex( { y: 1 } )
Both the insertOne() and the createIndex() operations create their
respective collection if they do not already exist.
Be sure that the collection name follows MongoDB Naming
Restrictions.
Databases and Collections
Create a Database
If a database does not exist, MongoDB creates the database when
you first store data for that database.
As such, you can switch to a non-existent database and perform the
following operation in mongosh:
use myNewDB
db.myNewCollection1.insertOne( { x: 1 } )
The insertOne() operation creates both the database myNewDB
and the collection myNewCollection1 if they do not already exist.
Be sure that both the database and collection names follow
MongoDB Naming Restrictions.
CRUD operations
Insert Documents
There are 2 methods to insert documents into a MongoDB database.
insertOne()
• To insert a single document, use the insertOne() method.
• This method inserts a single object into the database.

insertMany()
• To insert multiple documents at once, use the insertMany()
method.
• This method inserts an array of objects into the database.
Insert Documents
insertOne()
In MongoDB, insert operations target a single collection. All write
operations in MongoDB are atomic on the level of a single
document.
Insert Multiple
Documents
• db.collection.insertMany() can insert multiple documents into a
collection. Pass an array of documents to the method.
• If the documents do not specify an _id field, MongoDB adds the _id
field with an ObjectId value to each document.

db.inventory.insertMany([
{ item: "journal", qty: 25, tags: ["blank", "red"], size: { h: 14, w: 21,
uom: "cm" } },
{ item: "mat", qty: 85, tags: ["gray"], size: { h: 27.9, w: 35.5, uom:
"cm" } },
{ item: "mousepad", qty: 25, tags: ["gel", "blue"], size: { h: 19, w:
22.85, uom: "cm" } }
])
Read Operations

• Read operations retrieve documents from a collection; i.e. query a


collection for documents. MongoDB provides the following methods to
read documents from a collection:
db.collection.find()

• You can specify query filters or criteria that identify the documents to
return.
Read Operations

• Select All Documents in a Collection


db.collection.find()

• Specify Equality Condition


• To specify equality conditions, use <field>:<value> expressions
in the query filter document:
db.users.find({ status: "D" })
Read Operations

Specify Conditions Using Query Operators


• A query filter document can use the query operators to specify
conditions in the following form:

{ <field1>: { <operator1>: <value1> }, ... }

db.users.find({ status: { $in: [ "A", "D" ] } })


db.users.find({ qty: { $lt: 30 } })
db.users.find({ qty: { $gt: 30 } })

https://www.mongodb.com/docs/manual/reference/operator/query/
Read Operations

Specify AND Conditions


• A compound query can specify conditions for more than one field in
the collection's documents. Implicitly, a logical AND conjunction
connects the clauses of a compound query so that the query selects
the documents in the collection that match all the conditions.

• The following example retrieves all documents in the inventory


collection where the status equals "A" and qty is less than ($lt) 30:

db.users.find({ status: "A", qty: { $lt: 30 } })


Read Operations

Specify OR Conditions
• Using the $or operator, you can specify a compound query that joins
each clause with a logical OR conjunction so that the query selects the
documents in the collection that match at least one condition.

• The following example retrieves all documents in the collection where


the status equals "A" or qty is less than ($lt) 30:

db.users.find({ $or: [ { status: "A" }, { qty: { $lt:


30 } } ] })
Read Operations

Specify AND as well as OR Conditions


In the following example, the compound query document selects all
documents in the collection where the status equals "A" and either qty is
less than ($lt) 30 or item starts with the character p:

db.users.find({ status: "A", $or: [ { qty: { $lt: 30 } },


{ item: /^p/ } ] })
Read Operations

Query on Embedded/Nested Documents


To specify a query condition on fields in an embedded/nested document,
use dot notation ("field.nestedField").

db.users.find({ "size.uom": "in" })

db.users.find({ "size.h": { $lt: 15 } })

db.users.find({ size: { h: 14, w: 21, uom: "cm" } })


Read Operations

Query an Array
• To specify equality condition on an array, use the query document
{ <field>: <value> } where <value> is the exact array to match,
including the order of the elements.
• The following example queries for all documents where the field tags
value is an array with exactly two elements, "red" and "blank", in the
specified order:

db.inventory.find( { tags: ["red", "blank"] } )

• If, instead, you wish to find an array that contains both the elements
"red" and "blank", without regard to order or other elements in the
array, use the $all operator:
Read Operations

Query an Array
• the dim_cm array contains elements that in some combination satisfy
the query conditions; e.g., one element can satisfy the greater than 15
condition and another element can satisfy the less than 20 condition,
or a single element can satisfy both:

db.inventory.find( { dim_cm: { $gt: 15, $lt: 20 } } )

• Use $elemMatch operator to specify multiple criteria on the elements


of an array such that at least one array element satisfies all the
specified criteria.

db.inventory.find( { dim_cm: { $elemMatch: { $gt: 22, $lt:


30 } } } )
Update Operations
• Update operations modify existing documents in a collection.
• db.collection.updateOne() New in version 3.2
• db.collection.updateMany() New in version 3.2
• db.collection.replaceOne() New in version 3.2
• In MongoDB, update operations target a single collection. All
write operations in MongoDB are atomic on the level of a
single document.
• You can specify criteria, or filters, that identify the documents
to update.
Update Operations
Update a Single Document
• The following example uses the db.collection.updateOne() method on
the inventory collection to update the first document where item
equals "paper":
db.inventory.updateOne(
{ item: "paper" },
{ uses the $set operator to update the value
of the
$set: { "size.uom": "cm", status: "P" },size.uom field to "cm" and the value
of the status field to "P",
$currentDate: { lastModified: true }
} uses the $currentDate operator to update
the value of the lastModified field to the
) current date.
Update Operations
Update Multiple Documents

db.inventory.updateMany(
{ "qty": { $lt: 50 } },
{
uses the $set operator to update the value
$set: { "size.uom": "in", status: "P" },
of the size.uom field to "in" and the value of
$currentDate: { lastModified: true }the status field to "P",
}
uses the $currentDate operator to update
) the value of the lastModified field to the
current date.
Update Operations
Replace One Documents

db.inventory.replaceOne(
{ item: "paper" },
{ item: "paper", instock: [ { warehouse: "A", qty: 60 },
{ warehouse: "B", qty: 40 } ] }
)
Delete Operations
• Delete operations remove documents from a collection. MongoDB
provides the following methods to delete documents of a collection:
• db.collection.deleteOne() New in version 3.2
• db.collection.deleteMany() New in version 3.2
• In MongoDB, delete operations target a single collection. All write
operations in MongoDB are atomic on the level of a single document.
Connection
MongoClient
• Add the MongoDB Node.js Driver to your Node project dependencies
npm install mongodb
MongoClient
new MongoClient(url, options)
Creates a new MongoClient instance

Name Type Description


url string The connection URI string
options MongoClientOptions optionalOptional settings
MongoClient Methods

• MongoClient.connect(url, options)
• connect(callback)
• db(dbName, options)
• close(force, callback)
• isConnected(options)
Connect to MongoDB from
NodeJS
const { MongoClient, ServerApiVersion } = require('mongodb');
const uri
="mongodb+srv://psaikiran:[email protected]/";

// Create a MongoClient with a MongoClientOptions object to set the Stable


API version
const client = new MongoClient(uri, {
serverApi: {
version: ServerApiVersion.v1,
strict: true,
deprecationErrors: true,
}
});
Connect to MongoDB from
NodeJS
async function run() {
try {
// Connect the client to the server (optional starting in v4.7)
await client.connect();
// Send a ping to confirm a successful connection
await client.db("admin").command({ ping: 1 });
console.log("Pinged your deployment. You successfully connected to
MongoDB!");
} finally {
// Ensures that the client will close when you finish/error
await client.close();
}
}
run().catch(console.dir);
Insert One Document
through NodeJS

const myDB = client.db("myDB");


const myColl = myDB.collection("pizzaMenu");
const doc = { name: "Neapolitan pizza", shape: "round" };
const result = await myColl.insertOne(doc);
console.log(`A document was inserted with the _id: $
{result.insertedId}`,);
Insert Multiple Documents
through NodeJS
const myDB = client.db("myDB");
const myColl = myDB.collection("pizzaMenu");
const docs = [
{ name: "Sicilian pizza", shape: "square" },
{ name: "New York pizza", shape: "round" },
{ name: "Grandma pizza", shape: "square" }
];
const insertManyresult = await myColl.insertMany(docs);
let ids = insertManyresult.insertedIds;
console.log(`${insertManyresult.insertedCount} documents were
inserted.`);
for (let id of Object.values(ids)) {
console.log(`Inserted a document with id ${id}`);
}
Find a Document through
NodeJS

const myDB = client.db("myDB");


const myColl = myDB.collection("pizzaMenu");
const findResult = await myColl.find({shape:"square"});
for await(const doc of findResult)
{
console.log(doc);
}
Update a Document
through NodeJS

const myDB = client.db("myDB");


const myColl = myDB.collection("pizzaMenu");
const result = await myColl.updateOne({shape:"square"},{$set:
{shape:"Rectangle"}});
const findResult = await myColl.find({shape:"Rectangle"});
for await(const doc of findResult)
{
console.log(doc);
}
Delete a Document
through NodeJS

const myDB = client.db("myDB");


const myColl = myDB.collection("pizzaMenu");
const result = await myColl.deleteOne({shape:“Rectangle"});
const findResult = await myColl.find({shape:"Rectangle"});
for await(const doc of findResult)
{
console.log(doc);
}

You might also like