MongoDB Tutorial
MongoDB is a NoSQL document-oriented database that stores data in a flexible, JSON-like format. It is known for scalability, high performance, and the ability to handle unstructured data. MongoDB is commonly used in modern applications for its flexibility and ease of integration.
1. Installing MongoDBβ
Option 1: Download and Install MongoDBβ
- Go to the MongoDB website and download the latest MongoDB Community Server.
- Follow the installation instructions based on your operating system.
Option 2: Using Dockerβ
If you have Docker installed, you can run MongoDB in a container:
docker run -d --name mongodb -p 27017:27017 -e MONGO_INITDB_ROOT_USERNAME=mongoadmin -e MONGO_INITDB_ROOT_PASSWORD=secret mongo
This starts MongoDB on localhost:27017 with username mongoadmin and password secret.
2. Basic MongoDB Commandsβ
To connect to the MongoDB shell, run:
mongosh
Once connected, you can interact with the database.
Show All Databasesβ
show dbs
Select or Create a Databaseβ
use myDatabase
3. MongoDB Collections and Documentsβ
- Collection: A group of MongoDB documents, similar to a table in a relational database.
- Document: A single record in a MongoDB collection, stored in BSON (Binary JSON) format.
Example: Creating a Collectionβ
db.createCollection("users")
Example: Inserting a Documentβ
db.users.insertOne({ name: "Alice", age: 30, email: "alice@example.com" })
4. Querying Documentsβ
Retrieve data from a collection using find.
Example: Find All Documentsβ
db.users.find()
Example: Find Documents with a Conditionβ
db.users.find({ age: { $gt: 25 } })
This retrieves all users older than 25.
Projectionβ
Specify fields to include or exclude in the output.
db.users.find({}, { name: 1, _id: 0 })
5. Updating Documentsβ
Update existing documents using updateOne or updateMany.
Example: Update a Single Documentβ
db.users.updateOne({ name: "Alice" }, { $set: { age: 31 } })
Example: Update Multiple Documentsβ
db.users.updateMany({}, { $set: { active: true } })
6. Deleting Documentsβ
Remove documents using deleteOne or deleteMany.
Example: Delete a Single Documentβ
db.users.deleteOne({ name: "Alice" })
Example: Delete Multiple Documentsβ
db.users.deleteMany({ age: { $lt: 25 } })
7. Indexes in MongoDBβ
Indexes improve query performance by allowing MongoDB to quickly locate data.
Creating an Indexβ
db.users.createIndex({ name: 1 })
Viewing Indexesβ
db.users.getIndexes()
8. Using MongoDB with Node.jsβ
You can connect to MongoDB from a Node.js application using the MongoDB Node.js driver.
Step 1: Install MongoDB Driverβ
npm install mongodb
Step 2: Connect to MongoDBβ
const { MongoClient } = require("mongodb");
const uri = "mongodb://localhost:27017";
const client = new MongoClient(uri);
async function run() {
try {
await client.connect();
const database = client.db("myDatabase");
const users = database.collection("users");
// Insert a document
const result = await users.insertOne({ name: "Bob", age: 25 });
console.log(`New user created with id: ${result.insertedId}`);
} finally {
await client.close();
}
}
run().catch(console.error);
9. Aggregationβ
MongoDBβs aggregation framework allows complex data processing and transformations.
Example: Aggregation Pipelineβ
db.users.aggregate([
{ $match: { age: { $gte: 25 } } },
{ $group: { _id: "$age", count: { $sum: 1 } } }
])
This groups users by age and counts how many users fall into each age category.
10. Exporting and Importing Dataβ
Exporting Dataβ
To export a MongoDB collection to JSON or CSV:
mongoexport --db=myDatabase --collection=users --out=users.json
Importing Dataβ
To import data from a JSON file:
mongoimport --db=myDatabase --collection=users --file=users.json
Summaryβ
This tutorial covered MongoDB basics:
- Installing MongoDB and setting up a database.
- Creating collections and documents.
- Querying, updating, and deleting documents.
- Using MongoDB with Node.js for data operations.
- Using the aggregation framework for data analysis.
MongoDB is an excellent choice for applications that require flexible, scalable, and schema-less data storage.
Content Reviewβ
The content in this repository has been reviewed by chevp. Chevp is dedicated to ensuring that the information provided is accurate, relevant, and up-to-date, helping users to learn and implement programming skills effectively.
About the Reviewerβ
For more insights and contributions, visit chevp's GitHub profile: chevp's GitHub Profile.