NoSQL and MongoDB
NoSQL and MongoDB
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"]
}
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:
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/