MongoDB is a powerful, flexible database solution that allows for scalable data storage, making it popular for applications requiring a robust NoSQL database. This cheat sheet compiles key commands, structures, and examples to streamline your workflow.
1. Getting Started with MongoDB
Installation
To begin using MongoDB, follow these steps for installation:
For macOS:
brew tap mongodb/brew brew install mongodb-community
For Ubuntu:
sudo apt update sudo apt install -y mongodb
Starting the MongoDB Service
To start your MongoDB server, use the following command:
mongod
This launches your MongoDB server process. You can access the database from another terminal with:
mongo
2. Basic Commands
Checking the Database
To view your current databases:
show dbs
Creating a Database
To create a new database, you can use the use
command:
use myDatabase
This command switches to myDatabase
, creating it if it doesn’t exist.
Drop a Database
To delete a database permanently:
db.dropDatabase()
3. Collections
Create a Collection
Use the following command to create a collection:
db.createCollection('myCollection')
Drop a Collection
To remove an existing collection:
db.myCollection.drop()
List Collections
To see all collections in your current database:
show collections
4. CRUD Operations
Create (Insert Data)
Insert One Document
To insert a single document into a collection:
db.myCollection.insertOne({ name: "John Doe", age: 30 })
Insert Multiple Documents
To insert multiple records at once:
db.myCollection.insertMany([ { name: "Jane Doe", age: 25 }, { name: "Mike Smith", age: 35 } ])
Read (Query Data)
Find One Document
To retrieve a single document:
db.myCollection.findOne({ name: "John Doe" })
Find All Documents
To retrieve all documents in a collection:
db.myCollection.find()
Query with Conditions
You can filter results using conditions:
db.myCollection.find({ age: { $gte: 30 } })
This will find all documents where age is greater than or equal to 30.
Update (Modify Data)
Update One Document
To update a single document:
db.myCollection.updateOne( { name: "John Doe" }, { $set: { age: 31 } } )
Update Multiple Documents
To update multiple documents matching a condition:
db.myCollection.updateMany( { age: { $lt: 30 } }, { $set: { status: "young" } } )
Delete (Remove Data)
Delete One Document
To delete a single document:
db.myCollection.deleteOne({ name: "John Doe" })
Delete Multiple Documents
To delete multiple documents:
db.myCollection.deleteMany({ age: { $lt: 30 } })
5. Indexing
Create an Index
Indexes improve query performance. To create one, use:
db.myCollection.createIndex({ name: 1 })
This creates an ascending index on the name
field.
List Indexes
To view all indexes on a collection:
db.myCollection.getIndexes()
6. Aggregation Framework
The aggregation framework allows you to perform complex data processing tasks.
Basic Aggregation
To combine data from documents:
db.myCollection.aggregate([ { $match: { age: { $gte: 30 } } }, { $group: { _id: "$name", averageAge: { $avg: "$age" } } } ])
7. Backup and Restore
Backup Data
To create a backup of your database:
mongodump --db myDatabase --out /path/to/backup
Restore Data
To restore your database from a backup:
mongorestore /path/to/backup
8. Security
Create a User
To add a user with read and write permissions:
db.createUser({ user: "myUser", pwd: "myPassword", roles: [{ role: "readWrite", db: "myDatabase" }] })
Authentication
To require users to log in, start the server with:
mongod --auth
With this cheat sheet, you can quickly refer to essential MongoDB commands and concepts while developing your applications. Keep this handy as you navigate the powerful features that MongoDB offers!