Mongo db shell commands-2
Mongo db shell commands-2
Connection
mongo // Connect to local MongoDB instance
mongo --host <host> --port <port> -u <user> -p <password> // Connect with auth
db // Show current database
show dbs // List all databases
use <dbname> // Switch to/create database
Collections
show collections // List collections in current db
db.createCollection("name") // Create new collection
db.collection.drop() // Delete a collection
CRUD Operations
Create
db.collection.insertOne({key: value}) // Insert single document
db.collection.insertMany([{doc1}, {doc2}]) // Insert multiple documents
Read
db.collection.find() // Find all documents
db.collection.findOne({query}) // Find one document
db.collection.find({query}).pretty() // Pretty print results
db.collection.countDocuments({query}) // Count matching documents
Update
db.collection.updateOne({query}, {$set: {key: value}}) // Update one
db.collection.updateMany({query}, {$set: {key: value}}) // Update many
db.collection.replaceOne({query}, {newDocument}) // Replace document
Delete
db.collection.deleteOne({query}) // Delete one document
db.collection.deleteMany({query}) // Delete multiple documents
Query Operators
Comparison
db.collection.find({age: {$gt: 18}}) // Greater than
db.collection.find({age: {$gte: 18}}) // Greater than or equal
db.collection.find({age: {$lt: 65}}) // Less than
db.collection.find({age: {$lte: 65}}) // Less than or equal
db.collection.find({age: {$ne: 30}}) // Not equal
db.collection.find({age: {$in: [20, 30, 40]}}) // In array
Logical
db.collection.find({$and: [{cond1}, {cond2}]}) // AND
db.collection.find({$or: [{cond1}, {cond2}]}) // OR
db.collection.find({key: {$not: {condition}}}) // NOT
Element
db.collection.find({field: {$exists: true}}) // Field exists
db.collection.find({field: {$type: "string"}}) // Field type
Indexes
db.collection.createIndex({field: 1}) // Create ascending index
db.collection.createIndex({field: -1}) // Create descending index
db.collection.getIndexes() // List indexes
db.collection.dropIndex("indexName") // Drop index
Aggregation
db.collection.aggregate([
{$match: {status: "A"}}, // Filter documents
{$group: {_id: "$cust_id", total: {$sum: "$amount"}}}, // Group and sum
{$sort: {total: -1}}, // Sort results
{$limit: 5} // Limit results
])
Administration
db.createUser({user: "name", pwd: "pass", roles: ["readWrite"]}) // Create user
db.dropUser("username") // Delete user
db.grantRolesToUser("user", ["role"]) // Grant roles
db.revokeRolesFromUser("user", ["role"]) // Revoke roles
Utility
help // Show help
load("script.js") // Load and execute script
exit // Exit shell