Youcef Madadi
Web and game development teacher
Part 5 : MONGO THE DB
What is Mongo DB?
MongoDB is a source-available cross-platform document-oriented database program. Classified as a NoSQL database program, MongoDB uses JSON-like documents with optional schemas.
Key Features of MongoDB
Document-based storage: Stores data in BSON format (Binary JSON).
Flexible schema: No predefined schema is required.
Scalability: Horizontally scalable using sharding.
Rich querying: Supports complex queries and aggregation pipelines.
Indexing: Optimizes query performance with indexes.
MongoDB Components
Database: Contains collections.
Collection: Contains multiple documents.
Document: A JSON-like data structure.
{
"name": "Alice",
"age": 23
}
Start the mongodb server
> mongod
Opening mongodb's shell
> mongosh
Opening mongodb's shell from atlas url
> mongosh 'url'
get the list of instruction that you can make
> help
show the list of dbs in the server
> show dbs
Use/create a new database
> use $Dbname
Show collections
> show collections
DB methods
> db.help()
insert into/create collections
> db.collectionName.insert({
//parameters
})
insert into/create collections
db.cars.insertMany([
{ brand: "Ford", model: "Mustang", year: 2021, features: ["Cruise Control", "Navigation"] },
{ brand: "Tesla", model: "Model 3", year: 2023, features: ["Autopilot", "Electric"] },
]);
db.cars.insertOne({
brand: "Toyota",
model: "Corolla",
year: 2020,
features: ["Air Conditioning", "Bluetooth", "Backup Camera"],
});
db.cars.find({}, { brand: 1, model: 1, _id: 0 });
Only show brand and model (Projection)
db.cars.find({ year: { $gte: 2020 } });
Find cars from 2020 or newer
find data
db.cars.find();
update data
db.cars.updateOne({ model: "Corolla" }, { $set: { year: 2021 } });
update multiple data
db.cars.updateMany({ year: { $lt: 2020 } }, { $set: { status: "Outdated" } });
Delete data
db.cars.deleteOne({ model: "Mustang" });
Delete multiple data ( year older than 2015)
db.cars.deleteMany({ year: { $lt: 2015 } });
Exit mongodb shell
> exit
Indexes are a crucial component in MongoDB that optimize query performance. They allow MongoDB to quickly locate data within a collection, reducing the need to scan every document (a collection scan) when executing a query.
Index Only When Necessary
Use Compound Indexes Wisely
Monitor Index Usage
db.collection.stats()
and the Index Usage Statistics to identify unused indexes.Avoid Over-Indexing
Analyze Query Performance
explain()
to understand the impact of indexes on queries.Indexes improve query performance. Create indexes using `createIndex()`.
db.collection.createIndex({ fieldName: 1 });
db.students.createIndex({ name: 1 });
Create an index on `name` in the `students` collection:
When creating an index in MongoDB, you specify the sort order for the field(s) in the index as ascending (1
) or descending (-1
). This determines how the values in the indexed field are arranged within the index.
db.students.createIndex({ age: 1 });
db.students.find().sort({ age: 1 });
Ascending Order
When creating an index in MongoDB, you specify the sort order for the field(s) in the index as ascending (1
) or descending (-1
). This determines how the values in the indexed field are arranged within the index.
db.students.find().sort({ name: -1 });
db.students.find().sort({ name: -1 });
Descending Order
Combines multiple fields into a single index to support queries that filter or sort by those fields.
db.students.createIndex({ name: 1, age: -1 });
Ascending `name`, descending `age`
Supports indexing on array fields. Each array element is indexed separately.
db.articles.createIndex({ tags: 1 });
db.articles.createIndex({ description: "text" });
db.users.createIndex({ _id: "hashed" });
db.products.createIndex({ "details.$**": 1 });
In MongoDB, index options allow you to configure how an index behaves when created. These options can enforce specific constraints, optimize query performance, and manage how data is stored in the index.
Option | Description |
---|---|
unique | Ensures values in the indexed field(s) are unique. |
sparse | Indexes only documents with the indexed field. |
expireAfterSeconds | Sets a TTL for documents. |
partialFilterExpression | Indexes only documents that satisfy a condition. |
collation | Configures locale-specific and case-insensitive comparisons. |
background | Builds the index without blocking operations. |
name | Custom name for the index. |
default_language | Specifies the language for text indexes. |
weights | Sets the importance of fields in a text index. |
hidden | Makes the index inactive for queries unless explicitly hinted. |
db.collection.getIndexes();
db.collection.dropIndex("index_name");
db.collection.dropIndexes();
A transaction in MongoDB is a sequence of one or more operations that are executed as a single unit. Transactions ensure atomicity, consistency, isolation, and durability (ACID properties). This means that either all operations in the transaction are applied successfully, or none are applied, maintaining the integrity of your data.
const session = db.getMongo().startSession();
Start a Transaction: Use the startTransaction() method on the session object to begin the transaction.
session.startTransaction();
Perform Operations Within the Transaction: Any CRUD operations (insert, update, delete, etc.) that you want to be part of the transaction should use the session.
const accounts = session.getDatabase("bank").accounts;
accounts.updateOne({ accountNumber: 1 }, { $inc: { balance: -100 } }, { session });
accounts.updateOne({ accountNumber: 2 }, { $inc: { balance: 100 } }, { session });
Commit the Transaction: After performing all operations successfully, commit the transaction to apply the changes.
session.commitTransaction();
Abort the Transaction: If any operation fails or an error occurs, abort the transaction to roll back all changes.
session.abortTransaction();
End the Session: After committing or aborting the transaction, close the session.
session.endSession();
Install mongoose JS
> npm i mongoose
const mongoose=require("mongoose");
require mongoose JS
mongoose.connect('mongodb://localhost:27017/DBName');
connect to the database
Handle mongoose connection
mongoose.connect('mongodb://localhost:27017/Demo')
.then((connection) => {
console.log("db connected");
})
.catch((reason) => {
console.error(reason);
process.exit(-1);
});
mongoose.connect(URI,{ useNewUrlParser: true });
Use new URI parser
Create a schema
const mongoose =require( 'mongoose');
const { Schema } = mongoose;
const userSchema = new Schema({
first_name: String, // String is shorthand for {type: String}
last_name: String,
age:Number
});
const userModel=mongose.model("User",userSchema);
Create a model
Create a data
async function createData(first_name,last_name,age){
try{
const user = await userModel.create({first_name,last_name,age});
return user;
}catch(e){
return null;
}
}
Find data
async function findData(first_name){
try{
const users = await userModel.find({first_name});
return users;
}catch(e){
return [];
}
}
Find data
async function findData(first_name){
try{
const users = await userModel.find({first_name});
return users;
}catch(e){
return [];
}
}
Action Middleware
userSchema.pre('save', function() {
// do stuff
});
userSchema.post('save', function(docs) {
// do stuff
});
before saving
after saving
Action Middleware
Events
Instance Methods
userSchema.methods.findSimilarAge = function() {
return mongoose.models['User'].find({ age: this.age });
};
async function findSameAgeData(first_name){
try{
const user = await userModel.findOne({first_name});
return user.findSimilarAge();
}catch(e){
return [];
}
}
Static method
userSchema.statics.findAdults = function() {
return this.find({ age: {$gte : 19 } });
};
async function findAdultsData(){
try{
const adults = await userModel.findAdults();
return adults;
}catch(e){
return [];
}
}
By Youcef Madadi