Introduction to MongoDB
What is MongoDB?
MongoDB is a NoSQL document-oriented database. Unlike relational databases like MySQL or PostgreSQL, MongoDB stores data in JSON format (BSON, Binary JSON) instead of tables with rows and columns. It's ideal for applications that require schema flexibility and horizontal scalability.
Main features
- Document-oriented: Stores data in JSON/BSON format
- No fixed schema: Doesn't require defining structure beforehand
- Horizontal scalability: Easy to distribute across multiple servers
- Powerful queries: Supports complex searches and aggregations
- Indexes: Supports indexes to improve performance
Install MongoDB on Linux
On Ubuntu/Debian:
# Import GPG key
wget -qO - https://www.mongodb.org/static/pgp/server-6.0.asc | sudo apt-key add -
# Add repository
echo "deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu jammy/mongodb-org/6.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-6.0.list
# Install
sudo apt-get update
sudo apt-get install -y mongodb-org
# Start MongoDB
sudo systemctl start mongod
sudo systemctl enable mongod
On CentOS/RHEL:
# Create repository file
sudo nano /etc/yum.repos.d/mongodb-org-6.0.repo
# Add content:
[mongodb-org-6.0]
name=MongoDB Repository
baseurl=https://repo.mongodb.org/yum/redhat/$releasever/mongodb-org/6.0/x86_64/
gpgcheck=1
enabled=1
gpgkey=https://www.mongodb.org/static/pgp/server-6.0.asc
# Install
sudo yum install -y mongodb-org
# Start
sudo systemctl start mongod
sudo systemctl enable mongod
Verify installation
sudo systemctl status mongod
mongod --version
Connect to MongoDB
From terminal:
mongosh
Or with authentication:
mongosh -u user -p password --authenticationDatabase admin
Basic concepts
Database: Similar to MySQL, but you don't need to create it explicitly. It's created when inserting the first document.
Collection: Equivalent to a table in SQL. Contains documents.
Document: Equivalent to a row in SQL. It's a JSON/BSON object.
Field: Equivalent to a column in SQL. It's a property of the document.
Basic commands
See databases:
show dbs
Use a database:
use database_name
See collections:
show collections
Create a collection (implicit when inserting):
db.collection_name.insertOne({field: "value"})
Basic CRUD operations
Insert documents:
// Insert one document
db.users.insertOne({
name: "John",
email: "john@example.com",
age: 30
})
// Insert multiple documents
db.users.insertMany([
{name: "Mary", email: "mary@example.com", age: 25},
{name: "Peter", email: "peter@example.com", age: 35}
])
Query documents:
// Query all
db.users.find()
// Query with filter
db.users.find({name: "John"})
// Query one
db.users.findOne({age: {$gt: 30}})
// Query with readable format
db.users.find().pretty()
Update documents:
// Update one
db.users.updateOne(
{name: "John"},
{$set: {age: 31}}
)
// Update multiple
db.users.updateMany(
{age: {$lt: 30}},
{$set: {category: "young"}}
)
Delete documents:
// Delete one
db.users.deleteOne({name: "John"})
// Delete multiple
db.users.deleteMany({age: {$lt: 18}})
Common query operators
// Greater than
db.users.find({age: {$gt: 25}})
// Less than
db.users.find({age: {$lt: 40}})
// Greater or equal
db.users.find({age: {$gte: 18}})
// Less or equal
db.users.find({age: {$lte: 65}})
// Not equal
db.users.find({name: {$ne: "John"}})
// In array
db.users.find({category: {$in: ["admin", "moderator"]}})
// Not in array
db.users.find({category: {$nin: ["banned"]}})
// And logical
db.users.find({$and: [{age: {$gt: 18}}, {age: {$lt: 65}}]})
// Or logical
db.users.find({$or: [{name: "John"}, {name: "Mary"}]})
Indexes
Indexes improve query performance:
// Create index on a field
db.users.createIndex({email: 1})
// Create unique index
db.users.createIndex({email: 1}, {unique: true})
// Create compound index
db.users.createIndex({name: 1, age: -1})
// See indexes
db.users.getIndexes()
// Drop index
db.users.dropIndex({email: 1})
Aggregations
Aggregations allow processing and transforming data:
// Count documents
db.users.countDocuments({age: {$gt: 25}})
// Simple aggregation (equivalent to GROUP BY)
db.users.aggregate([
{$group: {_id: "$category", total: {$sum: 1}}}
])
// Aggregation with multiple stages
db.users.aggregate([
{$match: {age: {$gte: 18}}},
{$group: {_id: "$category", average: {$avg: "$age"}}},
{$sort: {average: -1}}
])
Configure authentication
1. Connect without authentication (first time):
mongosh
2. Create administrator user:
use admin
db.createUser({
user: "admin",
pwd: "secure_password",
roles: ["root"]
})
3. Enable authentication:
sudo nano /etc/mongod.conf
Uncomment or add:
security:
authorization: enabled
4. Restart MongoDB:
sudo systemctl restart mongod
Backup and restore
Backup:
mongodump --db database_name --out /path/backup/
Backup with authentication:
mongodump --db database_name -u user -p password --authenticationDatabase admin --out /path/backup/
Restore:
mongorestore --db database_name /path/backup/database_name/
Advantages and disadvantages
Advantages:
- Schema flexibility
- Easy horizontal scalability
- Fast for development
- Good performance with large data volumes
Disadvantages:
- Doesn't support complex transactions (though MongoDB 4.0+ supports them)
- Consumes more memory than relational databases
- Learning curve if coming from SQL
When to use MongoDB?
- Applications with frequently changing schemas
- User-generated content (social networks, blogs)
- Product catalogs with variable attributes
- Applications requiring horizontal scalability
- Data that doesn't fit well in relational tables
Need help?
If you have questions about MongoDB or need help configuring it, open a ticket from the billing.baires.host panel or contact us for support.
You can also reach us through our social media:
- Instagram: @baires_host
- Discord (active support): https://discord.gg/dzjauatAFN
- Linktree: https://linktr.ee/baires.host