Introduction to MongoDB
What is MongoDB?
MongoDB is a NoSQL document database that stores data in JSON like documents with flexible schemas. It's designed for scalability, performance, and developer productivity.
Key Features:
- Document-Oriented: Data stored as BSON (Binary JSON) documents
- Schema-Less: Flexible schema allows evolving data structures
- Distributed: Built-in sharding and replication
- Aggregation Pipeline: Powerful data processing framework
- ACID Transactions: Multi-document ACID transactions (v4.0+)
- Full-Text Search: Native text search capabilities
MongoDB Shell Basics
Essential commands to get started with MongoDB shell:
// Start MongoDB Shell
mongosh
// Check current database
db
// List all databases
show dbs
// Show current user
db.getUser()Connection Methods
MongoSh:
// Connect to local MongoDB
mongosh
// Connect to remote server
mongosh "mongodb://username:password@host:port/database"
// Connect to MongoDB Atlas
mongosh "mongodb+srv://username:password@cluster.mongodb.net/database"Compass:
// MongoDB Compass Connection String
mongodb://localhost:27017
// Connection with Authentication
mongodb://username:password@localhost:27017/database
// Atlas Connection
mongodb+srv://username:password@cluster.mongodb.net/databaseNode.js
// Using MongoDB Native Driver
const {
MongoClient
} = require('mongodb');
const client = new MongoClient('mongodb://localhost:27017');
await client.connect();
const db = client.db('myapp');
const collection = db.collection('users');