Backslash Commands Reference
Backslash Commands Reference
Section titled โBackslash Commands ReferenceโDBCrust provides a comprehensive set of backslash commands (meta-commands) that help you navigate and manage your database sessions efficiently. These commands are inspired by PostgreSQLโs psql but enhanced with modern features.
๐ Command Categories
Section titled โ๐ Command CategoriesโNavigation & Info
| Command | Description | Example |
|---|---|---|
\l | List databases | \l |
\dt | List tables | \dt |
\d [table] | Describe table or list all tables | \d users |
\c <database> | Connect to database | \c production |
\config | Show current configuration | \config |
Display & Output
| Command | Description | Example |
|---|---|---|
\x | Toggle expanded display | \x |
\e | Toggle EXPLAIN mode | \e |
\ecopy | Copy last EXPLAIN to clipboard | \ecopy |
\cs | Toggle column selection mode | \cs |
\csthreshold <n> | Set column selection threshold | \csthreshold 15 |
\clrcs | Clear saved column selections | \clrcs |
\resetview | Reset all view settings | \resetview |
\serverinfo | Toggle server info display | \serverinfo |
File Operations
| Command | Description | Example |
|---|---|---|
\w <file> | Write last script to file | \w query.sql |
\i <file> | Execute SQL file | \i setup.sql |
\ed | Edit query in external editor | \ed |
Named Queries
| Command | Description | Example |
|---|---|---|
\n | List named queries | \n |
\ns [--scope] <name> <query> [--scope] | Save named query with scope | \ns --global users SELECT * FROM users |
\nd <name> | Delete named query | \nd users |
Sessions & History
| Command | Description | Example |
|---|---|---|
\s [name] | List saved sessions or connect | \s or \s prod |
\ss <name> | Save current connection as session | \ss production |
\sd <name> | Delete saved session | \sd oldprod |
\r | List recent connections | \r |
\rc | Clear recent connections | \rc |
Vault Management
| Command | Description | Example |
|---|---|---|
\vc | Show vault credential cache status | \vc |
\vcc | Clear all cached vault credentials | \vcc |
\vcr [role] | Force refresh vault credentials | \vcr or \vcr my-role |
\vce | Show expired vault credentials | \vce |
Password Management
| Command | Description | Example |
|---|---|---|
\savepass | Save password to .dbcrust file (interactive) | \savepass |
\listpass | List stored passwords (without showing passwords) | \listpass |
\deletepass | Delete stored password (interactive selection) | \deletepass |
\encryptpass | Encrypt all plaintext passwords in .dbcrust | \encryptpass |
MongoDB Operations
| Command | Description | Example |
|---|---|---|
\collections | List collections in current database | \collections |
\dc <collection> | Describe collection structure | \dc users |
\dmi | List MongoDB indexes | \dmi |
\cmi <collection> <field> [type] | Create MongoDB index | \cmi users email |
\ddmi <collection> <index> | Drop MongoDB index | \ddmi users email_1 |
\mstats | Show MongoDB database statistics | \mstats |
\find <collection> [filter] [projection] [limit] | Execute MongoDB find query | \find users {"active": true} |
\aggregate <collection> <pipeline> | Execute MongoDB aggregation | \aggregate users [{"$match": {"active": true}}] |
\search <collection> <term> | MongoDB text search | \search articles "mongodb tutorial" |
Help & Control
| Command | Description | Example |
|---|---|---|
\h | Show help | \h |
\q | Quit DBCrust | \q |
๐ Detailed Command Reference
Section titled โ๐ Detailed Command ReferenceโNavigation Commands
Section titled โNavigation Commandsโ\l - List Databases
Section titled โ\l - List DatabasesโLists all databases on the current server.
\lOutput:
โญโโโโโโโโโโโโโโโฌโโโโโโโโโโโโฌโโโโโโโโโโโฌโโโโโโโโโโโโโโโโฎโ Name โ Owner โ Encoding โ Description โโโโโโโโโโโโโโโโโผโโโโโโโโโโโโผโโโโโโโโโโโผโโโโโโโโโโโโโโโโคโ myapp_dev โ postgres โ UTF8 โ Development โโ myapp_prod โ postgres โ UTF8 โ Production โโ analytics โ analyst โ UTF8 โ Data warehouseโโฐโโโโโโโโโโโโโโโดโโโโโโโโโโโโดโโโโโโโโโโโดโโโโโโโโโโโโโโโโฏ\dt - List Tables
Section titled โ\dt - List TablesโLists all tables in the current database.
\dtOutput:
โญโโโโโโโโโโโโโโฌโโโโโโโโโโโฌโโโโโโโโโโโฌโโโโโโโโโโโโโโฎโ Schema โ Name โ Type โ Owner โโโโโโโโโโโโโโโโผโโโโโโโโโโโผโโโโโโโโโโโผโโโโโโโโโโโโโโคโ public โ users โ table โ postgres โโ public โ orders โ table โ postgres โโ public โ products โ table โ postgres โโฐโโโโโโโโโโโโโโดโโโโโโโโโโโดโโโโโโโโโโโดโโโโโโโโโโโโโโฏ\d [table] - Describe Table
Section titled โ\d [table] - Describe TableโWithout arguments, lists all tables. With a table name, shows detailed table structure.
-- List all tables\d
-- Describe specific table\d usersOutput for \d users:
Table "public.users"โญโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโฌโโโโโโโโโโฌโโโโโโโโโโโโโโฎโ Column โ Type โ Nullable โ Default โ Description โโโโโโโโโโโโโโโโผโโโโโโโโโโโโโโโโโโโโโโผโโโโโโโโโโโโผโโโโโโโโโโผโโโโโโโโโโโโโโคโ id โ integer โ not null โ nextval โ Primary key โโ name โ character varying โ not null โ โ Full name โโ email โ character varying โ not null โ โ Email addr โโ created_at โ timestamp โ not null โ now() โ Created โโ status โ character varying โ โ active โ User status โโฐโโโโโโโโโโโโโโดโโโโโโโโโโโโโโโโโโโโโโดโโโโโโโโโโโโดโโโโโโโโโโดโโโโโโโโโโโโโโฏ
Indexes: "users_pkey" PRIMARY KEY, btree (id) "users_email_key" UNIQUE CONSTRAINT, btree (email) "idx_users_status" btree (status)\c <database> - Connect to Database
Section titled โ\c <database> - Connect to DatabaseโSwitches to a different database on the same server.
\c production_dbOutput:
You are now connected to database "production_db" as user "postgres".Display Commands
Section titled โDisplay Commandsโ\x - Toggle Expanded Display
Section titled โ\x - Toggle Expanded DisplayโSwitches between table and expanded (vertical) display formats.
\xBefore (table format):
โญโโโโโฌโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโโโโโฎโ id โ name โ email โโโโโโโผโโโโโโโโโโโผโโโโโโโโโโโโโโโโโโโโโโโคโ 1 โ John Doe โ john@example.com โโฐโโโโโดโโโโโโโโโโโดโโโโโโโโโโโโโโโโโโโโโโโฏAfter (expanded format):
-[ RECORD 1 ]----------id | 1name | John Doeemail | john@example.com\e - Toggle EXPLAIN Mode
Section titled โ\e - Toggle EXPLAIN ModeโEnables or disables automatic EXPLAIN for all queries.
\e -- Enable EXPLAIN mode
SELECT * FROM users WHERE email = 'john@example.com';Output with EXPLAIN enabled:
โ Execution Time: 0.89 msโ Planning Time: 0.12 ms
Index Scan using email_idx on usersโ Index Cond: (email = 'john@example.com'::text)โ โ Cost: 0.29..8.31 โ Rows: 1 โ Width: 156โโ Returns: id, name, email, created_at, status
โญโโโโโฌโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโโโโโฎโ id โ name โ email โโโโโโโผโโโโโโโโโโโผโโโโโโโโโโโโโโโโโโโโโโโคโ 1 โ John Doe โ john@example.com โโฐโโโโโดโโโโโโโโโโโดโโโโโโโโโโโโโโโโโโโโโโโฏEXPLAIN modes:
\e on -- Basic EXPLAIN\e analyze -- EXPLAIN ANALYZE\e verbose -- EXPLAIN VERBOSE\e buffers -- EXPLAIN (ANALYZE, BUFFERS)\e off -- Disable EXPLAIN\ecopy - Copy EXPLAIN to Clipboard
Section titled โ\ecopy - Copy EXPLAIN to ClipboardโCopies the last EXPLAIN plan in JSON format to your clipboard.
\ecopyOutput:
EXPLAIN plan copied to clipboard (JSON format)\cs - Toggle Column Selection Mode
Section titled โ\cs - Toggle Column Selection ModeโEnables or disables interactive column selection for all queries. When enabled, all queries will prompt for column selection regardless of the number of columns.
\cs -- Toggle column selection mode on/offOutput:
Column selection is now enabled.\csthreshold <number> - Set Column Selection Threshold
Section titled โ\csthreshold <number> - Set Column Selection ThresholdโConfigures the number of columns that triggers automatic column selection. This setting is saved to your configuration file.
-- Set threshold to 15 columns\csthreshold 15
-- Set threshold to 5 columns for detailed work\csthreshold 5Output:
Column selection threshold set to: 15Default threshold: 10 columns
Interactive Column Selection Interface
Section titled โInteractive Column Selection InterfaceโWhen column selection is triggered (either automatically or via \cs mode), an interactive interface appears:
Features:
- Visual Selection: Checkbox-style interface with arrow key navigation
- Multi-Select: Use spacebar to select/deselect multiple columns
- Keyboard Controls:
- โ/โ Arrow keys: Navigate between columns
- Space: Toggle column selection
- Enter: Confirm selection and show results
- Ctrl+C: Abort query and return to prompt (doesnโt exit DBCrust)
Example Usage:
-- This query has 11 columns, exceeds default threshold of 10SELECT * FROM users_detailed;Interactive Interface:
? Select columns to display:โฏ โฏ id โฏ username โฏ email โฏ first_name โฏ last_name โฏ created_at โฏ updated_at โฏ last_login โฏ is_active โฏ phone โฏ address[โโ to move, space to select, enter to confirm, ctrl+c to abort]After selection (e.g., selecting id, username, email):
Showing 3 of 11 columnsโญโโโโโฌโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโโโโโฎโ id โ username โ email โโโโโโโผโโโโโโโโโโโผโโโโโโโโโโโโโโโโโโโโโโโคโ 1 โ john_doe โ john@example.com โโ 2 โ jane_doe โ jane@example.com โโฐโโโโโดโโโโโโโโโโโดโโโโโโโโโโโโโโโโโโโโโโโฏSession Persistence
Section titled โSession PersistenceโColumn selections are automatically remembered during your session:
Behavior:
- Selections saved per table structure (based on column names)
- Subsequent queries on same table use saved selection automatically
- Persists until you clear selections or reset views
Example:
-- First time: interactive selection appearsSELECT * FROM users_detailed;-- [Select id, username, email]
-- Second time: uses saved selection automaticallySELECT * FROM users_detailed WHERE created_at > '2024-01-01';-- Shows only id, username, email columns\clrcs - Clear Column Selections
Section titled โ\clrcs - Clear Column SelectionsโRemoves all saved column selections, returning to fresh selection state for all tables.
\clrcsOutput:
Column views cleared.After clearing, the next query on any table will prompt for column selection again.
\resetview - Reset All View Settings
Section titled โ\resetview - Reset All View SettingsโResets all display settings to defaults, including:
- Column selections (clears all saved selections)
- Expanded display mode (
\x) - EXPLAIN mode (
\e)
\resetviewOutput:
View settings reset to defaults.File Operations
Section titled โFile Operationsโ\w <filename> - Write Script to File
Section titled โ\w <filename> - Write Script to FileโSaves the last executed query or script to a file.
-- Execute a querySELECT * FROM users WHERE created_at > '2024-01-01';
-- Save it to file\w recent_users.sqlOutput:
Script written to 'recent_users.sql' (156 bytes)\i <filename> - Execute SQL File
Section titled โ\i <filename> - Execute SQL FileโLoads and executes SQL commands from a file.
\i setup_tables.sqlFile contents (setup_tables.sql):
CREATE TABLE IF NOT EXISTS users ( id SERIAL PRIMARY KEY, name VARCHAR(255) NOT NULL, email VARCHAR(255) UNIQUE NOT NULL, created_at TIMESTAMP DEFAULT NOW());
INSERT INTO users (name, email) VALUES('Alice Johnson', 'alice@example.com'),('Bob Smith', 'bob@example.com');Output:
Executing setup_tables.sql...CREATE TABLEINSERT 0 2Script execution completed successfully.\ed - External Editor
Section titled โ\ed - External EditorโOpens your default editor to write or edit a query.
\edProcess:
- Opens
$EDITOR(vim, nano, code, etc.) - Edit your query
- Save and close
- Script is loaded and ready - press Enter to execute
Editor integration:
# Set preferred editorexport EDITOR="code --wait" # VS Codeexport EDITOR="vim" # Vimexport EDITOR="nano" # NanoWorkflow tip: After using \ed or \i, press Enter on an empty line to re-execute the last loaded script.
Named Queries
Section titled โNamed QueriesโDBCrust provides a powerful scoped named query system that allows you to organize queries by visibility scope: global, database-type specific, or session-local.
Query Scopes
Section titled โQuery ScopesโGlobal Scope - Available across all database connections and sessions Database-Type Scope - Available only for specific database types (PostgreSQL, MySQL, SQLite) Session-Local Scope - Available only for the current database session (host+port+database+user)
\n - List Named Queries
Section titled โ\n - List Named QueriesโShows all named queries available in the current context, with scope indicators.
\nOutput:
Named queries: active_users [global] - SELECT * FROM users WHERE status = 'active' pg_stats [postgres] - SELECT * FROM pg_stat_activity daily_summary [session] - SELECT DATE(created_at), COUNT(*) FROM orders user_report [global] - SELECT u.*, COUNT(o.id) FROM users u LEFT JOIN orders o ON u.id = o.user_idScope Priority: Session-local queries take precedence over database-type queries, which take precedence over global queries when names conflict.
\ns [--scope] <name> <query> [--scope] - Save Named Query with Scope
Section titled โ\ns [--scope] <name> <query> [--scope] - Save Named Query with ScopeโSaves a query with a name and optional scope specification. Supports parameter substitution.
Scope Options:
-g/--global- Available for all database connections--postgres- Available only for PostgreSQL connections--mysql- Available only for MySQL connections--sqlite- Available only for SQLite connections- No flag (default) - Session-local scope (current database session only)
Scope flags can be placed before the name, between the name and query, or after the query.
Basic Examples:
-- Session-local query (default)\ns active_users SELECT * FROM users WHERE status = 'active'
-- Global query - flag before name (recommended)\ns --global count_all SELECT COUNT(*) FROM $1
-- Global query - flag after query (also works)\ns count_all SELECT COUNT(*) FROM $1 --global
-- PostgreSQL-specific query\ns --postgres pg_activity SELECT * FROM pg_stat_activity
-- MySQL-specific query\ns --mysql mysql_status SHOW GLOBAL STATUS LIKE 'Connections'
-- SQLite-specific query\ns --sqlite sqlite_tables SELECT name FROM sqlite_master WHERE type='table'Parameter Substitution:
-- Single parameter\ns --global user_by_id SELECT * FROM users WHERE id = $1
-- Multiple parameters\ns user_orders SELECT * FROM orders WHERE user_id = $1 AND status = '$2'
-- All remaining parameters (space-separated)\ns --global search_users SELECT * FROM users WHERE name ILIKE '%$*%'
-- All remaining parameters (single string)\ns full_search SELECT * FROM users WHERE CONCAT(first_name, ' ', last_name) ILIKE '%$@%'Advanced Scope Examples:
-- Database-type specific reporting queries\ns --postgres pg_table_sizes SELECT schemaname, tablename, pg_size_pretty(pg_total_relation_size(schemaname||'.'||tablename)) as size FROM pg_tables
\ns --mysql mysql_table_info SELECT table_name, table_rows, data_length FROM information_schema.tables WHERE table_schema = DATABASE()
-- Global utility queries\ns --global today_records SELECT * FROM $1 WHERE DATE(created_at) = CURRENT_DATE
-- Session-specific queries (no flag needed)\ns my_analysis SELECT customer_id, SUM(amount) FROM local_sales_data GROUP BY customer_idQuery Execution:
-- Execute named queries with parametersactive_usersuser_by_id 123user_orders 123 completedsearch_users John Doepg_table_sizesSave Confirmation:
Named query 'active_users' saved successfully (scope: session-local).Named query 'pg_activity' saved successfully (scope: postgres).Named query 'count_all' saved successfully (scope: global).\nd <name> - Delete Named Query
Section titled โ\nd <name> - Delete Named QueryโRemoves a named query from the current context. Automatically detects the scope of the query to delete.
\nd active_usersOutput:
Named query 'active_users' deleted successfully (scope: session-local).Scope Resolution: When deleting, DBCrust follows the same priority order as execution - it will delete the session-local query first, then database-type, then global if multiple queries exist with the same name.
Practical Usage Patterns
Section titled โPractical Usage PatternsโDevelopment Workflow:
-- Create session-specific analysis queries during development\ns debug_orders SELECT * FROM orders WHERE created_at > '2024-01-01' AND status = 'pending'
-- Create global utilities for reuse across projects\ns --global table_info SELECT table_name, table_rows FROM information_schema.tables WHERE table_schema = '$1'
-- Create database-specific maintenance queries\ns --postgres pg_vacuum_analyze VACUUM ANALYZE $1Team Collaboration:
-- Global queries shared across team\ns --global daily_metrics SELECT DATE(created_at), COUNT(*), AVG(amount) FROM orders WHERE created_at >= CURRENT_DATE - INTERVAL '7 days' GROUP BY DATE(created_at)
-- Database-specific performance queries\ns --postgres pg_slow_queries SELECT query, calls, total_time, mean_time FROM pg_stat_statements ORDER BY mean_time DESC LIMIT 10Multi-Database Projects:
-- PostgreSQL analytics\ns --postgres user_engagement SELECT user_id, COUNT(*) as actions FROM user_events WHERE created_at > $1 GROUP BY user_id
-- MySQL equivalent\ns --mysql user_engagement SELECT user_id, COUNT(*) as actions FROM user_events WHERE created_at > '$1' GROUP BY user_id
-- Global fallback\ns --global simple_count SELECT COUNT(*) FROM $1Autocomplete Support
Section titled โAutocomplete SupportโThe named query system provides intelligent autocomplete:
Query Name Completion:
\n act[TAB] -- Shows: active_users\ns my_qu[TAB] -- Shows existing query names for overwriting\nd debug[TAB] -- Shows: debug_ordersScope Flag Completion:
\ns --glo[TAB] -- Shows: --global (at start)\ns myquery SELECT 1 --post[TAB] -- Shows: --postgres (at end)SQL Completion:
\ns myquery SELE[TAB] -- Shows: SELECT, SELECT *, etc.\ns myquery SELECT * FROM use[TAB] -- Shows: users tableStorage and Migration
Section titled โStorage and MigrationโNamed queries are stored separately by scope:
- Global: Available across all sessions and database types
- Database-type: Available for all sessions of that database type
- Session-local: Available only for the specific database session
Storage Location: ~/.config/dbcrust/named_queries.toml
Migration: Existing named queries from older versions are automatically migrated to the new scoped system as global queries during the first run.
Session Management
Section titled โSession Managementโ\s [name] - List or Connect to Sessions
Section titled โ\s [name] - List or Connect to SessionsโWithout arguments, lists all saved sessions. With a session name, connects to that session.
-- List all saved sessions\sOutput:
Saved Sessions: production - PostgreSQL postgres@prod.db.com:5432/myapp staging - PostgreSQL postgres@staging.db.com:5432/myapp_staging local_mysql - MySQL root@localhost:3306/testdb analytics - SQLite /data/analytics.db
Use 'session://<name>' to connect via command line-- Connect to a saved session\s productionOutput:
Connecting to saved session 'production'...โ Successfully connected to database\ss <name> - Save Session
Section titled โ\ss <name> - Save SessionโSaves the current connection as a named session for quick reconnection.
\ss productionOutput:
Session 'production' saved successfully\sd <name> - Delete Session
Section titled โ\sd <name> - Delete SessionโRemoves a saved session.
\sd old_stagingOutput:
Deleted session 'old_staging'Connection History
Section titled โConnection Historyโ\r - List Recent Connections
Section titled โ\r - List Recent ConnectionsโShows your recent connection history with full URLs (excluding passwords).
\rOutput:
Recent Connections: [1] โ docker://postgres@myapp-postgres/myapp_dev - 2024-01-15 14:22 (PostgreSQL) [2] โ postgres://user@localhost:5432/testdb - 2024-01-15 14:15 (PostgreSQL) [3] โ mysql://root@badhost:3306/db - 2024-01-15 14:10 (MySQL) [4] โ sqlite:///home/user/data.db - 2024-01-15 13:55 (SQLite)
Use 'recent://' to interactively select and connect to a recent connection\rc - Clear Recent Connections
Section titled โ\rc - Clear Recent ConnectionsโClears all connection history.
\rcOutput:
Cleared all recent connectionsConfiguration savedVault Management
Section titled โVault ManagementโDBCrust provides intelligent caching for HashiCorp Vault dynamic credentials to improve performance and reduce Vault API calls.
\vc - Show Vault Credential Cache Status
Section titled โ\vc - Show Vault Credential Cache StatusโDisplays all cached Vault credentials with their expiration status and remaining TTL.
\vcOutput:
Vault credential cache status (showing 2 entries): database/myapp-prod/readonly (v-user-prod--ABC123-1234567890) - 0h58m remaining - VALID database/myapp-dev/admin (v-user-dev--XYZ789-9876543210) - 0h02m remaining - EXPIRES SOONStatus indicators:
- VALID: Credentials have sufficient TTL remaining
- EXPIRES SOON: Credentials below renewal threshold (default: 25% of original TTL)
- EXPIRED: Credentials past expiration time (automatically cleaned up)
\vcc - Clear Vault Credential Cache
Section titled โ\vcc - Clear Vault Credential CacheโRemoves all cached vault credentials, forcing fresh authentication on next vault:// connection.
\vccOutput:
Cleared all cached vault credentials (2 entries removed)\vcr [role] - Force Refresh Vault Credentials
Section titled โ\vcr [role] - Force Refresh Vault CredentialsโForces refresh of Vault credentials, either for all cached entries or a specific role.
-- Refresh all cached credentials\vcr
-- Refresh specific role\vcr readonlyOutput:
Refreshed vault credentials for role 'readonly'New credentials valid for 1h0mUse cases:
- Force credential renewal before long-running operations
- Refresh credentials that are near expiration
- Update credentials after Vault policy changes
\vce - Show Expired Vault Credentials
Section titled โ\vce - Show Expired Vault CredentialsโLists vault credentials that have expired but havenโt been cleaned up yet.
\vceOutput:
Expired vault credentials (1 entry): database/myapp-staging/readonly - expired 0h15m agoVault Credential Caching Behavior
Section titled โVault Credential Caching BehaviorโAutomatic Caching:
- Credentials are automatically cached when using
vault://URLs - Cache persists between DBCrust sessions
- Stored in encrypted file:
~/.config/dbcrust/vault_credentials.enc
Cache Validation:
- Credentials are checked for expiration before use
- TTL threshold prevents using credentials that expire soon (default: 5 minutes minimum)
- Automatic cleanup removes expired credentials
Security Features:
- All cached credentials are encrypted using AES-256-GCM
- Encryption key derived from your Vault token
- Cache automatically invalidated if Vault token changes
Configuration:
vault_credential_cache_enabled = true # Enable/disable cachingvault_cache_renewal_threshold = 0.25 # Renew when 25% TTL remainingvault_cache_min_ttl_seconds = 300 # Minimum 5 minutes requiredExample Workflow
Section titled โExample Workflowโ-- First connection: fetches and caches credentialsdbcrust vault://readonly@database/myapp-prod
-- Check cache status\vc-- Output: database/myapp-prod/readonly (v-user--ABC123-1234567890) - 0h59m remaining - VALID
-- Reconnect quickly using cached credentialsdbcrust vault://readonly@database/myapp-prod-- Uses cached credentials, no Vault API call
-- Force refresh if needed\vcr readonly
-- Clear cache when done\vccMongoDB Operations
Section titled โMongoDB OperationsโDBCrust provides comprehensive MongoDB support with both native MongoDB commands and familiar SQL-like syntax for database and collection management.
SQL Database Management Commands
Section titled โSQL Database Management CommandsโMongoDB database and collection operations can be performed using familiar SQL syntax:
Database Operations:
-- Create a new databaseCREATE DATABASE analytics;
-- Drop an existing databaseDROP DATABASE old_analytics;Collection Operations:
-- Create a new collectionCREATE COLLECTION user_profiles;
-- Drop an existing collectionDROP COLLECTION temp_data;\collections - List Collections
Section titled โ\collections - List CollectionsโLists all collections in the current MongoDB database.
\collectionsOutput:
โญโโโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโฎโ Collection โ Type โโโโโโโโโโโโโโโโโโโโผโโโโโโโโโโโโโโโคโ users โ collection โโ orders โ collection โโ products โ collection โโ sessions โ collection โโฐโโโโโโโโโโโโโโโโโโดโโโโโโโโโโโโโโโฏ\dc <collection> - Describe Collection
Section titled โ\dc <collection> - Describe CollectionโShows the structure and sample documents from a MongoDB collection.
\dc usersOutput:
Collection: usersSample Documents: 3
Field Structure:โญโโโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโฎโ Field โ Type โ Sample Value โโโโโโโโโโโโโโโโโโโโผโโโโโโโโโโโโโโโผโโโโโโโโโโโโโโโคโ _id โ ObjectId โ 507f1f77... โโ email โ String โ user@email.com โโ name โ String โ John Doe โโ active โ Boolean โ true โโ created_at โ DateTime โ 2024-01-15 โโฐโโโโโโโโโโโโโโโโโโดโโโโโโโโโโโโโโโดโโโโโโโโโโโโโโโฏMongoDB-Specific Commands
Section titled โMongoDB-Specific Commandsโ\dmi - List MongoDB Indexes:
\dmiShows all indexes across collections in the current database.
\cmi <collection> <field> [type] - Create Index:
-- Create standard index\cmi users email
-- Create text index for search\cmi articles content text\search <collection> <term> - Text Search:
-- Search for documents containing specific terms\search articles "mongodb tutorial"
-- Search with multiple terms\search products "wireless bluetooth"Advanced MongoDB Queries
Section titled โAdvanced MongoDB QueriesโDBCrust supports advanced SQL-to-MongoDB translation with sophisticated filtering:
LIKE Pattern Matching:
-- SQL LIKE translates to MongoDB $regexSELECT * FROM users WHERE name LIKE 'John%';-- โ MongoDB: {"name": {"$regex": "John.*", "$options": "i"}}IN Operator:
-- SQL IN translates to MongoDB $inSELECT * FROM orders WHERE status IN ('pending', 'processing');-- โ MongoDB: {"status": {"$in": ["pending", "processing"]}}OR Conditions:
-- SQL OR translates to MongoDB $orSELECT * FROM users WHERE age > 18 OR verified = true;-- โ MongoDB: {"$or": [{"age": {"$gt": 18}}, {"verified": true}]}BETWEEN Ranges:
-- SQL BETWEEN translates to MongoDB $gte + $lteSELECT * FROM products WHERE price BETWEEN 10 AND 100;-- โ MongoDB: {"price": {"$gte": 10, "$lte": 100}}NULL Handling:
-- SQL IS NULL/IS NOT NULL translates to MongoDB $existsSELECT * FROM users WHERE email IS NOT NULL;-- โ MongoDB: {"email": {"$exists": true, "$ne": null}}MongoDB Workflow Example
Section titled โMongoDB Workflow Exampleโ-- Connect to MongoDBdbcrust mongodb://localhost:27017/myapp
-- List collections\collections
-- Examine a collection structure\dc users
-- Query with advanced filteringSELECT * FROM usersWHERE name LIKE 'John%' AND age BETWEEN 18 AND 65 AND status IN ('active', 'verified');
-- Create collection with SQL syntaxCREATE COLLECTION user_sessions;
-- Drop collection when no longer neededDROP COLLECTION temp_analytics;
-- Create index for better performance\cmi users email
-- Perform text search\search users "john developer"๐ก Advanced Usage Patterns
Section titled โ๐ก Advanced Usage PatternsโCombining Commands
Section titled โCombining Commandsโ-- Switch database and list tables\c analytics\dt
-- Enable EXPLAIN and run query\e onSELECT COUNT(*) FROM large_table;
-- Save result and write to file\w large_table_count.sqlScripting Workflows
Section titled โScripting Workflowsโ-- Create a setup script\ed
-- In editor, write:-- \c development-- \i create_tables.sql-- \i seed_data.sql-- \dt
-- Save and execute automaticallyQuery Development
Section titled โQuery Developmentโ-- Start with simple querySELECT * FROM users LIMIT 5;
-- Refine in editor\ed
-- Save final version\w final_user_report.sql
-- Create named query for reuse\ns user_report SELECT u.*, COUNT(o.id) as order_count FROM users u LEFT JOIN orders o ON u.id = o.user_id GROUP BY u.id