MongoDB
π MongoDB Cheat Sheet
[!info] 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-org
Red 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 MongoDB
macOS / Linux
sudo systemctl start mongod
π§ͺ Access MongoDB Shell
mongo
π» Basic MongoDB Commands
[!tip]
Use these commands within themongo
shell 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
[!note] You can connect programmatically using drivers for:
Check out: MongoDB Drivers
π Related
π Explore More
π·οΈ Tags π
#mongodb #nosql #database #mongo