Mongo db Shell Commands
MongoDB shell commands allow you to interact with a MongoDB database from the command-line interface using the mongosh
shell. Below is a categorized list of commonly used commands:
Basic MongoDB Shell Commands
- Start the MongoDB Shellmongosh
- Show Available Databasesshow dbs
- Switch to a Databaseuse databaseName
- Show Current Databasedb
Collection Commands
- Show Collections in the Current Databaseshow collections
- Create a Collectiondb.createCollection("collectionName")
- Drop a Collectiondb.collectionName.drop()
Insert Data
- Insert a Single Document
db.collectionName.insertOne({ key1: "value1", key2: "value2" }) - Insert Multiple Documentsdb.collectionName.insertMany([{ key1: "value1", key2: "value2" },{ key1: "value3", key2: "value4" }])
Query Data
- Find All Documents
db.collectionName.find() - Find with a Filter
db.collectionName.find({ key1: "value1" }) - Find One Documentdb.collectionName.findOne({ key1: "value1" })
- Limit Resultsdb.collectionName.find().limit(5)
- Sort Results
db.collectionName.find().sort({ key1: 1 }) // 1 for ascending, -1 for descending
Update Data
- Update a Single Document
- Update Multiple Documents
- Replace a Document
Delete Data
- Delete a Single Document
- Delete Multiple Documents
Indexing
- Create an Index
- View All Indexes
- Drop an Index
Aggregation
- Simple Aggregation Pipeline
Administrative Commands
- Check Server Status
- View Current Operations
- Kill an Operation
These commands cover basic CRUD operations, indexing, and administrative tasks. Let me know if you want to dive deeper into any specific area!