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

  1. Start the MongoDB Shell
    mongosh
  2. Show Available Databases
    show dbs

  3. Switch to a Database
    use databaseName
  4. Show Current Database
    db

Collection Commands

  1. Show Collections in the Current Database
    show collections
  2. Create a Collection
    db.createCollection("collectionName")
  3. Drop a Collection
    db.collectionName.drop()

Insert Data

  1. Insert a Single Document
    db.collectionName.insertOne({ key1: "value1", key2: "value2" })

  2. Insert Multiple Documents
    db.collectionName.insertMany([
        { key1: "value1", key2: "value2" },
        { key1: "value3", key2: "value4" }
        ])


Query Data

  1. Find All Documents
    db.collectionName.find()

  2. Find with a Filter
    db.collectionName.find({ key1: "value1" })

  3. Find One Document
    db.collectionName.findOne({ key1: "value1" })
  4. Limit Results
    db.collectionName.find().limit(5)
  5. Sort Results
    db.collectionName.find().sort({ key1: 1 }) // 1 for ascending, -1 for descending

Update Data

  1. Update a Single Document
    db.collectionName.updateOne( { key1: "value1" }, // Filter { $set: { key2: "newValue" } } // Update )
  2. Update Multiple Documents
    db.collectionName.updateMany(
    { key1: "value1" }, { $set: { key2: "newValue" } } )
  3. Replace a Document
    db.collectionName.replaceOne(
    { key1: "value1" }, { key1: "newKey", key2: "newValue" } )

Delete Data

  1. Delete a Single Document
    db.collectionName.deleteOne({ key1: "value1" })
  2. Delete Multiple Documents
    db.collectionName.deleteMany({ key1: "value1" })

Indexing

  1. Create an Index
    db.collectionName.createIndex({ key1: 1 }) // 1 for ascending, -1 for descending
  2. View All Indexes
    db.collectionName.getIndexes()
  3. Drop an Index

    db.collectionName.dropIndex("indexName")

Aggregation

  1. Simple Aggregation Pipeline
    db.collectionName.aggregate([ { $match: { key1: "value1" } }, { $group: { _id: "$key2", total: { $sum: "$key3" } } } ])

Administrative Commands

  1. Check Server Status
    db.serverStatus()
  2. View Current Operations
    db.currentOp()
  3. Kill an Operation
    db.killOp(opId)

These commands cover basic CRUD operations, indexing, and administrative tasks. Let me know if you want to dive deeper into any specific area!