Basic MongoDB Commands
Starting and Stopping the MongoDB Server
- Starting MongoDB:
- Windows: Run
mongod
in Command Prompt. If installed as a service, it might start automatically. - macOS/Linux: Run
mongod
in Terminal.
- Windows: Run
- Stopping MongoDB:
- Windows: Press
Ctrl+C
in the Command Prompt wheremongod
is running. - macOS/Linux: Press
Ctrl+C
in the Terminal wheremongod
is running. Alternatively, usesudo systemctl stop mongod
for system service.
- Windows: Press
Basic MongoDB Shell Commands (mongo
)
- Connecting to MongoDB Shell:
- Run
mongo
in 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" })