Basic MongoDB Commands
Starting and Stopping the MongoDB Server
- Starting MongoDB:
- Windows: Run
mongodin Command Prompt. If installed as a service, it might start automatically. - macOS/Linux: Run
mongodin Terminal.
- Windows: Run
- Stopping MongoDB:
- Windows: Press
Ctrl+Cin the Command Prompt wheremongodis running. - macOS/Linux: Press
Ctrl+Cin the Terminal wheremongodis running. Alternatively, usesudo systemctl stop mongodfor system service.
- Windows: Press
Basic MongoDB Shell Commands (mongo)
- Connecting to MongoDB Shell:
- Run
mongoin Command Prompt or Terminal to start the MongoDB shell.
- Run
- Basic Commands:
- Show Databases:
show dbs- Example:
> show dbs
- Example:
- Use a Database:
use <dbName>- Example:
> use myDatabase
- Example:
- Create a Collection: This happens implicitly when inserting documents.
- Show Collections:
show collections- Example:
> show collections
- Example:
- Show Databases:
Insert a Document:
> db.myCollection.insertOne({ name: "John", age: 30 })
Find Documents:
> db.myCollection.find()
Update a Document:
> db.myCollection.updateOne({ name: "John" }, { $set: { age: 31 } })
Delete a Document:
> db.myCollection.deleteOne({ name: "John" })