๐ MongoDB Cheat Sheet
MongoDB is a flexible, scalable NoSQL document database used widely in modern application development. It stores data in JSON-like documents, making it ideal for unstructured or semi-structured data.
โ๏ธ Installation
๐ช Windows
-
Download MongoDB from the official website.
-
Run the installer and follow the setup wizard.
๐ macOS
Install via Homebrew:
brew tap mongodb/brew
brew install mongodb-community๐ง Linux
Ubuntu / Debian
sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 9DA31620334BD75D9DCB49F368818C72E52529D4
echo "deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu $(lsb_release -cs)/mongodb-org/5.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-5.0.list
sudo apt-get update
sudo apt-get install -y mongodb-orgRed Hat / CentOS
- Create a repo file:
sudo vi /etc/yum.repos.d/mongodb-org-5.0.repo- Add:
[mongodb-org-5.0]
name=MongoDB Repository
baseurl=https://repo.mongodb.org/yum/redhat/$releasever/mongodb-org/5.0/x86_64/
gpgcheck=1
enabled=1
gpgkey=https://www.mongodb.org/static/pgp/server-5.0.asc- Then:
sudo yum install -y mongodb-org๐ Starting the MongoDB Service
Windows
mongod --install
net start MongoDBmacOS / Linux
sudo systemctl start mongod๐งช Access MongoDB Shell
mongo๐ป Basic MongoDB Commands
Tip
Use these commands within the
mongoshell unless otherwise specified.
๐ Show Databases
show dbs๐งญ Switch/Create Database
use your_database_name๐๏ธ Create a Collection
db.createCollection("your_collection_name")๐งพ Insert Document
db.your_collection_name.insertOne({ key1: "value1", key2: "value2" })๐ Find Documents
db.your_collection_name.find()๐ Find with Filter
db.your_collection_name.find({ key: "value" })๐ ๏ธ Update One Document
db.your_collection_name.updateOne(
{ key: "value" },
{ $set: { new_key: "new_value" } }
)๐ ๏ธ Update Multiple Documents
db.your_collection_name.updateMany(
{ key: "value" },
{ $set: { new_key: "new_value" } }
)โ Delete One Document
db.your_collection_name.deleteOne({ key: "value" })โ Delete Multiple Documents
db.your_collection_name.deleteMany({ key: "value" })๐ง Notes
You can connect programmatically using drivers for:
Check out: MongoDB Drivers