MongoDB is a popular NoSQL database that provides a flexible and scalable solution for storing and managing data. Unlike traditional relational databases, MongoDB uses a document-oriented data model, making it well-suited for handling unstructured or semi-structured data.
/data/db
directory. Create this directory if it does not exist.mongod
command.mongo
command.
# Start MongoDB server
mongod
# Connect to MongoDB shell
mongo
mongod
starts the MongoDB server. This command needs to be run in the terminal to initiate the MongoDB server process.mongo
connects to the MongoDB shell. This shell allows you to interact with the MongoDB server using JavaScript-like syntax. You can perform various database operations, such as querying, inserting, updating, and deleting data.To create a new database in MongoDB, you can use the use
command. If the database does not exist, MongoDB will create it automatically when you insert data into it.
// Use a database named "mydatabase"
use mydatabase
Collections in MongoDB are analogous to tables in relational databases. You can create a new collection using the db.createCollection()
method.
// Create a collection named "users"
db.createCollection("users")
You can insert documents into a collection using the insertOne()
or insertMany()
methods.
// Insert a single document into the "users" collection
db.users.insertOne({ name: "John", age: 30 })
// Insert multiple documents into the "users" collection
db.users.insertMany([
{ name: "Alice", age: 25 },
{ name: "Bob", age: 35 }
])
insertOne()
method inserts a single document into the “users” collection. The document is represented as a JSON object with key-value pairs.insertMany()
method inserts multiple documents into the “users” collection. It takes an array of documents as input and inserts them all into the collection.MongoDB provides various methods for querying documents, such as find()
, findOne()
, and aggregate()
.
// Find all documents in the "users" collection
db.users.find()
// Find documents where the age is greater than 25
db.users.find({ age: { $gt: 25 } })
// Find a single document with the name "Alice"
db.users.findOne({ name: "Alice" })
find()
method retrieves all documents in the “users” collection. If no parameters are provided, it returns all documents.find()
method with a query filter. Here, we’re finding documents where the “age” field is greater than 25.findOne()
method returns a single document that matches the specified query criteria. In this example, it finds a document where the “name” field is “Alice”.To update documents in MongoDB, you can use the updateOne()
or updateMany()
methods.
// Update the age of the document with name "John"
db.users.updateOne({ name: "John" }, { $set: { age: 32 } })
// Update the age of all documents where age is less than 30
db.users.updateMany({ age: { $lt: 30 } }, { $set: { age: 30 } })
updateOne()
method updates a single document that matches the specified filter. In this example, it updates the age of the user named “John” to 32.updateMany()
method, we can update multiple documents that match the specified filter. Here, we’re incrementing the age of users younger than 30 by 1.You can delete documents from a collection using the deleteOne()
or deleteMany()
methods.
// Delete the document with name "Alice"
db.users.deleteOne({ name: "Alice" })
// Delete all documents where age is equal to 30
db.users.deleteMany({ age: 30 })
deleteOne()
method deletes a single document that matches the specified filter. Here, it deletes the document where the name is “Bob”.deleteMany()
method deletes multiple documents that match the specified filter. In this example, it deletes documents of users aged 40 or older.MongoDB’s Aggregation Framework allows for advanced data processing and analysis tasks.
// Group documents by a specified field and calculate aggregate values
db.sales.aggregate([
{ $group: { _id: "$product", totalSales: { $sum: "$amount" } } }
])
// Filter documents based on a condition and perform aggregation
db.sales.aggregate([
{ $match: { date: { $gte: new Date("2022-01-01"), $lt: new Date("2022-02-01") } } },
{ $group: { _id: "$product", totalSales: { $sum: "$amount" } } }
])
$group
stage groups input documents by a specified expression and outputs a document for each distinct grouping. In the first example, it groups documents by the “product” field and calculates the total sales for each product.$sum
operator calculates the sum of numeric values. Here, it’s used to sum the “amount” field values.$match
stage, then group them by product to calculate total sales.Indexes in MongoDB improve query performance by allowing the database to quickly locate data without scanning the entire collection.
// Create an index on the "username" field
db.users.createIndex({ username: 1 })
// Create a compound index on multiple fields
db.orders.createIndex({ customer_id: 1, date: -1 })
// List all indexes on a collection
db.users.getIndexes()
createIndex()
method creates an index on the specified field(s) of a collection. In the first example, an index is created on the “username” field in ascending order.getIndexes()
method retrieves a list of all indexes on a collection.MongoDB’s GridFS is a specification for storing and retrieving large files such as images, audio files, and video files.
// Upload a file to GridFS
const fs = require('fs');
const data = fs.readFileSync('largefile.mp4');
const fileId = db.fs.files.insertOne({ filename: 'largefile.mp4' }).insertedId;
db.fs.chunks.insertOne({ files_id: fileId, data });
// Download a file from GridFS
const file = db.fs.files.findOne({ _id: fileId });
const data = db.fs.chunks.find({ files_id: fileId }).sort({ n: 1 }).toArray();
fs.writeFileSync(file.filename, Buffer.concat(data.map(chunk => chunk.data)));
fs.files
collection, and then insert the file data into the fs.chunks
collection in chunks.fs.files
using its ID, then fetch the corresponding chunks from fs.chunks
and concatenate them into the original file.we provided an introduction to MongoDB, covering its installation, basic operations, and usage. MongoDB offers a flexible and scalable solution for storing and managing data, making it a popular choice for modern applications. By mastering the fundamental concepts and operations of MongoDB, you can effectively leverage its capabilities to build robust and efficient database-driven applications. Happy Coding!❤️