MongoDB Shell Command Reference and Query Operations

Server Initialization

mongod --dbpath /var/lib/mongodb
# Alternative path syntax
./mongod --dbpath /data/db

Ensure the executable has sufficient file system permissions. A successful launch outputs waiting for connections on port 27017.

Client Access

Navigate to the installation bin directory. Launch the interactive interpreter by executing mongo or opaning a terminal directly within that folder.

Database Management

Direct interaction begins with contextual switches and metadata inspection.

Command Function
help General shell documentation
db.help() Context-specific database helpers
db.coll_ref.help() Collection method assistance
show dbs List initialized databases
use target_db Switch context or provision a new database
db Display current active database
db.stats() Return storage metrics
db.version() Report server version
db.getMongo() Show connection endpoint
db.dropDatabase() Permanently remove active database

Note: Empty databases do not appear in show dbs until they contain at least one document.

Collection Operations

// Standard initialization
db.createCollection('staff_records')

// Capped collection configuration (circular overwrite mechanism)
db.createCollection('audit_logs', { 
  capped: true, 
  size: 5242880, 
  max: 5000 
})
/* Key parameters:
   capped: Boolean | Activates fixed-size storage
   autoIndexId: Boolean | Manages implicit _id indexing (false by default)
   size: Number | Byte capacity limit for capped sets
   max: Number | Absolute document ceiling */

db.getCollection('staff_records')
db.getCollectionNames()
db.printCollectionStats()

Document Insertion

Modern drivers prefer explicit one-or-many methods over legacy wrappers.

// Single record insertion
db.staff_records.insertOne({ 
  name: 'Alice Chen', 
  role: 'DevOps', 
  level: 1, 
  age: 29, 
  region: 'West' 
})

// Batch payload submission
db.staff_records.insertMany([
  { name: 'Bob Smith', role: 'Frontend', level: 2, age: 34, region: 'East' },
  { name: 'Carol Lee', role: 'Backend', level: 1, age: 26, region: 'North' }
])

// Conditional insert/update hybrid (replaces if _id exists)
db.staff_records.save({ name: 'David Kim', role: 'QA Lead', level: 3, age: 41, region: 'South' })

Data Retrieval & Filtering

// Raw and formatted output
db.staff_records.find()
db.staff_records.find().pretty()

// Exact matching
db.staff_records.find({ name: 'Alice Chen' })

// Field projection (1=include, 0=exclude)
db.staff_records.find({ role: 'Backend' }, { name: 1, level: 1, _id: 0 })

// Numeric ranges
db.staff_records.find({ age: { $gte: 30, $lte: 40 } }, { name: 1, age: 1, _id: 0 })

// Pattern matching
db.staff_records.find({ name: /^Alice/ })

// Unique value extraction
db.staff_records.distinct('region')

// Row count
db.staff_records.countDocuments()

Record Modification

// Target single match
db.staff_records.updateOne(
  { name: 'Alice Chen' },
  { $set: { level: 2 } }
)

// Atomic arithmetic increment
db.staff_records.updateOne(
  { name: 'Bob Smith' },
  { $inc: { level: 1 } }
)

// Multi-document update
db.staff_records.updateMany(
  { role: { $in: ['Frontend', 'Backend'] } },
  { $set: { dept: 'Engineering' } }
)

// Broadcast assignment across all matches
db.staff_records.updateMany({}, { $set: { status: 'Active' } })

Deletion Protocols

db.staff_records.deleteOne({ name: 'Carol Lee' })
db.staff_records.deleteMany({ age: { $lt: 30 } })
db.staff_records.deleteMany({})

Advanced Query Modifiers

Chaining operators allows precise pagination and execution planning.

// Ascending/Descending sort
db.staff_records.find().sort({ age: -1 })

// Offset and page size control
db.staff_records.find().skip(10).limit(5)

// Bulk conversion
db.staff_records.find().toArray()

Additional cursor capabilities include .collation(), .hint(), .explain(), .batchSize(), .min(), and .maxScan(). Iterative processing remains accessible through .next(), .hasNext(), .forEach(), and .close().

Tags: mongodb Database-Administration shell-commands crud-operations NoSQL

Posted on Mon, 20 Jul 2026 17:46:55 +0000 by gm04030276