Fullstack > Tools > 🗄️ MongoDB
MongoDB
MongoDB is a popular NoSQL database designed for scalability and flexibility. This guide will help you install MongoDB on your system and set up a basic database.
Step 1: Download MongoDB
- Go to the official MongoDB Download Center.
- Select the latest Community Server version for your operating system.
- Download and install MongoDB following the provided instructions.
Step 2: Install MongoDB
On Windows:
- Run the downloaded
.msifile. - Follow the installation wizard and select Complete Installation.
- Ensure the MongoDB Database Server option is checked.
- Optionally, install MongoDB Compass (GUI tool for MongoDB).
- Complete the installation and restart your system if necessary.
On macOS:
- Open the terminal and install MongoDB using Homebrew:
brew tap mongodb/brew brew install mongodb-community@6.0 - Start the MongoDB service:
brew services start mongodb-community@6.0 - Verify installation:
mongod --version
On Linux (Ubuntu/Debian):
- Import the MongoDB public key:
wget -qO - https://www.mongodb.org/static/pgp/server-6.0.asc | sudo apt-key add - - Add the MongoDB repository:
echo "deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu focal/mongodb-org/6.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-6.0.list - Update package lists and install MongoDB:
sudo apt update sudo apt install -y mongodb-org - Start MongoDB service:
sudo systemctl start mongod - Enable MongoDB to start on boot:
sudo systemctl enable mongod
Step 3: Verify MongoDB Installation
Run the following command to check if MongoDB is running:
mongo --eval 'db.runCommand({ connectionStatus: 1 })'
Step 4: Create and Use a Database
- Open the MongoDB shell:
mongo - Create a new database:
use mydatabase - Insert a document into a collection:
db.users.insertOne({ name: "John Doe", age: 30 }) - Retrieve the document:
db.users.find().pretty()
Step 5: Run an Example Node.js MongoDB Connection
- Install the MongoDB Node.js driver:
npm install mongodb - Create a new JavaScript file
app.js:const { MongoClient } = require('mongodb'); const uri = "mongodb://localhost:27017"; const client = new MongoClient(uri); async function run() { try { await client.connect(); console.log("Connected to MongoDB"); const database = client.db("mydatabase"); const users = database.collection("users"); const user = await users.findOne({ name: "John Doe" }); console.log(user); } finally { await client.close(); } } run().catch(console.error); - Run the script:
node app.js
Conclusion
You have successfully installed MongoDB, created a database, and connected it with a Node.js application. You can now start developing applications using MongoDB!