0% found this document useful (0 votes)
28 views24 pages

NoSQL and MongoDB

The document provides an overview of MongoDB, a free and open-source NoSQL database that stores data in flexible, JSON-like documents. It covers installation options, data structure, CRUD operations, and aggregation queries, emphasizing the schema-less nature of collections and the automatic creation of collections upon document insertion. Key features include support for multiple programming languages and the ability to connect to both local and cloud-based servers.

Uploaded by

Sharjeel Sajid
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)
28 views24 pages

NoSQL and MongoDB

The document provides an overview of MongoDB, a free and open-source NoSQL database that stores data in flexible, JSON-like documents. It covers installation options, data structure, CRUD operations, and aggregation queries, emphasizing the schema-less nature of collections and the automatic creation of collections upon document insertion. Key features include support for multiple programming languages and the ability to connect to both local and cloud-based servers.

Uploaded by

Sharjeel Sajid
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/ 24

Written in C++, C and JavaScript

• It’s free and open-source

Stores data in flexible, JSON-like documents


• In an analogy, instead of rows, we have documents
and instead of tables, we have collections
MongoDB

Compatible languages are


• Python
• Java
• C++
• C#
• JavaScript
Server
• Local Install
• Using the open source community server
• https://www.mongodb.com/docs/manual/installation/
Installations
• Cloud Based
• MongoDB Atlas
• https://www.mongodb.com/atlas
• Add IP address to the allow remote access

Client
• Mongosh (
https://www.mongodb.com/docs/mongodb-shell/install/)
Connecting to the Server (Local)
• Default Host: localhost
• Default Port: 27017
mongosh
• Or
mongosh "mongodb://localhost:27017"

• Remote Server

mongosh "mongodb://your-server-ip:27017"
Connecting to the Server (Atlas
Cluster)
• https://www.mongodb.com/docs/atlas/connect-to-database-deploym
ent/#use-the-connect-dialog-to-connect-to-your-cluster
Working with Databases
• Show all Databases
show dbs
• Create/Select a Database
use myAwesomeDatabase
• If the db does not exist yet, it will be created in memory
• In MongoDB, a database is only persisted when it gets content
• Show Current DB
db
MongoDB Data Structure
• Data is stored in BSON (Binary representation of JSON) format
• https://bsonspec.org/
• Example Document:

{
"_id": "uniqueID123",
"name": { "first": "John", "last": "Doe" },
"age": 30,
"hobbies": ["reading", "traveling"]
}

•_id is the primary key, automatically generated if not provided.


Collections
• A collection is a group of documents (JSON-like objects) that are
stored in a database.
• Collections are analogous to tables in relational databases, but they
are more flexible since they do not require a fixed schema.
• Key Characteristics of Collections
• Schema-Less: Collections can store documents with varying fields and
structures.
{ "_id": 1, "name": "Alice", "age": 25 }
{ "_id": 2, "title": "Book", "author": "John Doe", "pages": 300 }
Types of Collections
• Capped Collections
• A capped collection is a fixed-size collection in MongoDB.
• When the collection reaches its maximum size or document count, it
overwrites the oldest entries with new ones.
• These collections are designed for high-throughput operations like logging or
caching.
• Clustered Collections
• A clustered collection in MongoDB organizes and stores documents in order
based on a clustered index key.
• This is not capped—it doesn’t overwrite data but provides ordered storage
for faster range queries.

https://www.mongodb.com/docs/manual/reference/method/db.createCollection/#mongodb-method-db.createCollection
Adding a document to your
database.
Step 1: Open MongoDB Shell
Connect to your MongoDB server using the shell:
mongosh
Step 2: Switch to Your Database
Use the use command to select your database. If the database doesn’t exist, MongoDB will
create it when you add a document:
use mydatabase
Step 3: Add a Document to a Collection
Option 1: Add a Single Document
To add a single document to a collection (e.g., mycollection), use the insertOne() method:
db.mycollection.insertOne({
name: "Alice",
age: 25,
hobbies: ["reading", "traveling"]
});
Add Multiple Documents
To add multiple documents at once, use the insertMany() method:

db.mycollection.insertMany([
{ name: "Bob", age: 30, hobbies: ["sports", "music"] },
{ name: "Carol", age: 22, hobbies: ["art", "gaming"] }
]);
Verify the Insertion
To check if the document(s) were added successfully, use the find() method:
db.mycollection.find();

Example Output:

{ "_id": ObjectId("unique-id-1"), "name": "Alice", "age": 25, "hobbies":


["reading", "traveling"] }
{ "_id": ObjectId("unique-id-2"), "name": "Bob", "age": 30, "hobbies":
["sports", "music"] }
{ "_id": ObjectId("unique-id-3"), "name": "Carol", "age": 22, "hobbies":
["art", "gaming"] }
Key Points
1.Collections Are Auto-Created:
• If mycollection doesn’t exist, MongoDB creates it when you add the first
document.
2._id Field:
• MongoDB automatically adds an _id field to each document as a unique
identifier. You can specify your own _id if needed.
db.mycollection.insertOne({
_id: 101,
name: "David",
age: 28
});

3. Dynamic Schema:
• Documents in the same collection can have different fields and
structures.
Aggregation query in MongoDB
Check the Documents in Your Collection Aggregation Query:
db.mycollection.find();
[ db.mycollection.aggregate([ { $match: { age: { $gt:
{ 25 } } }] );
_id: ObjectId('674e95f41cf8a35dcf6d78f1'), Result:
name: 'Alice', [
age: 25, {
hobbies: [ 'reading', 'traveling' ] _id: ObjectId('674e96061cf8a35dcf6d78f2'),
}, name: 'Bob',
{ age: 30,
_id: ObjectId('674e96061cf8a35dcf6d78f2'), hobbies: [ 'sports', 'music' ]
name: 'Bob', }
age: 30, ]
hobbies: [ 'sports', 'music' ]
},
{
_id: ObjectId('674e96061cf8a35dcf6d78f3'),
name: 'Carol',
age: 22,
hobbies: [ 'art', 'gaming' ]
}
]
CRUD Operations – Create
• Can use the following methods to insert documents into a collection,
db.collection.insertOne()
db.collection.insertMany()
CRUD Operations – Read
• Can use the following methods to read documents from a collection,
db.collection.find()
db.collection.find().pretty() (To view data in formatted JSON)
CRUD Operations – Update
• Can use the following methods to update documents in a collection,
db.collection.updateOne()
db.collection.updateMany()
db.collection.replaceOne()
CRUD Operations – Delete
• Can use the following methods to update documents in a collection,
db.collection.deleteOne()
db.collection.deleteMany()
Aggregation Pipelines
• An aggregation pipeline consists of one or more stages that process
documents:
• Each stage performs an operation on the input documents.
• For example, a stage can filter documents, group documents, and calculate values.
• The documents that are output from a stage are passed to the next stage.
• An aggregation pipeline can return results for groups of documents.
• For example, return the total, average, maximum, and minimum values.
Aggregation Expressions
• https://www.mongodb.com/docs/manual/reference/operator/aggreg
ation/#std-label-aggregation-expression-operators
Aggregation Pipeline Example
[ db.sales.aggregate([
{ "_id": 1, "product": "Apple", "category": "Fruit", // Stage 1: Filter documents (keep only Fruits)
{ $match: { category: "Fruit" } },
"quantity": 5, "price": 2 },
{ "_id": 2, "product": "Banana", "category": "Fruit", // Stage 2: Group documents by category
"quantity": 10, "price": 1 }, {
$group: {
{ "_id": 3, "product": "Carrot", "category": "Vegetable", _id: "$category", // Group by 'category'
"quantity": 8, "price": 3 }, totalQuantity: { $sum: "$quantity" }, // Sum of 'quantity'
{ "_id": 4, "product": "Broccoli", "category": "Vegetable", avgPrice: { $avg: "$price" }, // Average of 'price'
"quantity": 7, "price": 2 }, maxPrice: { $max: "$price" }, // Maximum 'price'
minPrice: { $min: "$price" } // Minimum 'price'
{ "_id": 5, "product": "Strawberry", "category": "Fruit", }
"quantity": 4, "price": 4 } }
] ]);

Result:
You want to: [
{
1. Filter only the documents in the Fruit category.
"_id": "Fruit",
2. Group the documents by category. "totalQuantity": 19,
3. Calculate the total quantity, average price, maximum price, "avgPrice": 2.3333333333333335,
and minimum price for the Fruit category. "maxPrice": 4,
"minPrice": 1
}
]
Lastly
• Visit the manual for any help,
• https://docs.mongodb.com/manual/

• And practice…
That’s all
References
• https://en.wikipedia.org/wiki/NoSQL
• https://www.mongodb.com/

You might also like