Setting Up MongoDB on WSL
Prerequisites:
- Windows 10/11 with WSL2 installed
- Ubuntu or Debian distribution in WSL
- VS Code installed (optional)
1. Update System
Update package lists to ensure latest versions and avoid compatibility issues.
2. Import MongoDB Repository Key
MongoDB isn't in Ubuntu's default repositories. Import MongoDB's official GPG key to verify authenticity.
curl -fsSL https://www.mongodb.org/static/pgp/server-7.0.asc | \
sudo gpg -o /usr/share/keyrings/mongodb-server-7.0.gpg --dearmor
3. Add MongoDB Repository
Tell Ubuntu's package manager where to find MongoDB packages.
echo "deb [ arch=amd64,arm64 signed-by=/usr/share/keyrings/mongodb-server-7.0.gpg ] https://repo.mongodb.org/apt/ubuntu jammy/mongodb-org/7.0 multiverse" | \
sudo tee /etc/apt/sources.list.d/mongodb-org-7.0.list
sudo apt-get update
4. Install MongoDB
Install the complete MongoDB database system including server, shell, and tools.
Verify installation:
5. Create Data Directory
MongoDB requires a directory to store database files. Default location is /data/db.
# Create directory
sudo mkdir -p /data/db
# Set ownership to your user
sudo chown -R $USER:$USER /data/db
# Verify permissions
ls -ld /data/db
Expected output: drwxr-xr-x ... /data/db
6. Start MongoDB Server
Method 1: Using systemctl
# Start MongoDB service
sudo systemctl start mongod
# Check status
sudo systemctl status mongod
# Enable auto-start on boot (optional)
sudo systemctl enable mongod
Look for "Active: active (running)" in status output.
Method 2: Manual start (if systemctl doesn't work)
Flags:
- --dbpath /data/db - Data storage location
- --fork - Runs in background
- --logpath - Log file location
7. Connect to MongoDB Shell
Launch MongoDB shell to interact with databases.
Expected output:
The test> prompt indicates connection success.
8. Test MongoDB Operations
Run these commands inside mongosh:
Check current database:
Create database:
Insert document:
Query documents:
Insert multiple documents:
db.users.insertMany([
{ name: "Bob", age: 32, city: "Durrës" },
{ name: "Carol", age: 25, city: "Vlorë" }
])
Count documents:
Query with filter:
Update document:
Delete document:
Show collections:
Show databases:
Exit shell:
9. Stop MongoDB Server
Or if started manually:
10. VS Code Integration (Optional)
Install extension:
- Open VS Code
- Extensions (Ctrl+Shift+X)
- Search "MongoDB for VS Code"
- Install official extension
Connect:
- Click MongoDB icon in sidebar
- Add Connection
- Enter:
mongodb://localhost:27017 - Connect
Features: Browse databases, run queries, view documents, export/import data.
Verification Commands
# Check versions
mongod --version
mongosh --version
# Verify service
sudo systemctl status mongod
# Test connection
mongosh --eval "db.version()"