MongoDB is a document-oriented NoSQL database that uses a BSON (Binary JSON) format to store data. It is highly scalable and flexible.
MongoDB Installation
Installation on Windows
Download the installer from the official page and follow the instructions.
Data Structure
Documents and Collections
- A document is an individual record, similar to a row in a relational database.
- A collection is a set of documents, comparable to a table.
{
"_id": ObjectId("607d1c4e79b1f8d75e7ecf0b"),
"name": "Luis",
"age": 30,
"city": "Madrid"
}
Connecting to MongoDB
Connect to the Database
Use the MongoDB shell to connect to a database:
mongo --host localhost --port 27017
Connection from Node.js
Install the MongoDB driver:
npm install mongodb
Connect from Your Application:
const { MongoClient } = require('mongodb');
const url = 'mongodb://localhost:27017';
const client = new MongoClient(url);
async function run() {
try {
await client.connect();
console.log("Successfully connected to the database");
} finally {
await client.close();
}
}
run().catch(console.dir);
CRUD Operations
Insert a Document
const result = await collection.insertOne({ name: "Luis", age: 30 });
console.log(`New document created with id: ${result.insertedId}`);
Insert Multiple Documents
const result = await collection.insertMany([
{ name: "Ana", age: 25 },
{ name: "Pedro", age: 35 }
]);
console.log(`${result.insertedCount} documents were inserted`);
Find a Document
const document = await collection.findOne({ name: "Luis" });
console.log(document);
Find Multiple Documents
const documents = await collection.find({ age: { $gt: 30 } }).toArray();
console.log(documents);
Update a Document
const result = await collection.updateOne(
{ name: "Luis" },
{ $set: { age: 31 } }
);
console.log(`${result.modifiedCount} document(s) updated`);
Update Multiple Documents
const result = await collection.updateMany(
{ age: { $lt: 30 } },
{ $set: { status: "young" } }
);
console.log(`${result.modifiedCount} document(s) updated`);
Delete a Document
const result = await collection.deleteOne({ name: "Luis" });
console.log(`${result.deletedCount} document(s) deleted`);
Delete Multiple Documents
const result = await collection.deleteMany({ age: { $lt: 30 } });
console.log(`${result.deletedCount} document(s) deleted`);
Advanced Operations
Aggregations
MongoDB allows for complex aggregation operations:
const results = await collection.aggregate([
{ $match: { age: { $gte: 25 } } },
{ $group: { _id: "$city", averageAge: { $avg: "$age" } } }
]).toArray();
console.log(results);
Indexes
Indexes improve query performance:
await collection.createIndex({ name: 1 });
List Indexes
const indexes = await collection.indexes();
console.log(indexes);
Filtering and Searching
Common Query Operators
Operator | Description | Example |
---|---|---|
$eq | Equal to | { age: { $eq: 30 }} |
$gt | Greater than | { age: { $gt: 25 }} |
$gte | Greater than or equal to | { age: { $gte: 25 }} |
$lt | Less than | { age: { $lt: 25 }} |
$lte | Less than or equal to | { age: { $lte: 25 }} |
$ne | Not equal to | { age: { $ne: 30 }} |
$in | In a set of values | { city: { $in: ["Madrid", "Barcelona"] }} |
$or | Or | { $or: [{ age: 25 }, { city: "Madrid" }] } |
$and | And | { $and: [{ age: { $gte: 25 } }, { city: "Madrid" }] } |
Security and Authentication
User Authentication
You can create users and assign roles:
db.createUser({
user: "user",
pwd: "password",
roles: [{ role: "readWrite", db: "myDatabase" }]
});
Connection with Authentication
const url = 'mongodb://user:password@localhost:27017/myDatabase';