MongoDB Guide
MongoDB Guide
Section titled “MongoDB Guide”DBCrust provides comprehensive MongoDB support with a familiar SQL-like interface that translates to native MongoDB operations. This guide covers everything from basic connections to advanced querying and database management.
🚀 Getting Started with MongoDB
Section titled “🚀 Getting Started with MongoDB”Connection Methods
Section titled “Connection Methods”DBCrust supports multiple MongoDB connection methods:
Standard MongoDB
# Local MongoDB instancedbcrust mongodb://localhost:27017/myapp
# With authenticationdbcrust mongodb://user:password@localhost:27017/myapp
# With connection optionsdbcrust mongodb://user:pass@localhost:27017/myapp?authSource=adminMongoDB Atlas
# MongoDB Atlas with SRV recorddbcrust mongodb+srv://user:password@cluster.mongodb.net/myapp
# Atlas with specific optionsdbcrust mongodb+srv://user:pass@cluster.mongodb.net/myapp?retryWrites=trueDocker Container
# Interactive container selectiondbcrust docker://
# Direct MongoDB container connectiondbcrust docker://mongodb-devdbcrust docker://mongo-container/myappSession Management
# Save MongoDB connection as sessiondbcrust mongodb://localhost:27017/myapp\ss mongo_local
# Reconnect using sessiondbcrust session://mongo_localFirst Steps
Section titled “First Steps”After connecting to MongoDB, explore your database:
-- List all collections (equivalent to "tables" in SQL)\collections
-- Examine a collection's structure\dc users
-- List database statistics\mstats
-- Simple query to see dataSELECT * FROM users LIMIT 5;🔍 SQL-to-MongoDB Query Translation
Section titled “🔍 SQL-to-MongoDB Query Translation”DBCrust’s key feature is translating familiar SQL syntax into MongoDB operations seamlessly.
Basic SELECT Queries
Section titled “Basic SELECT Queries”-- SQL syntax that everyone knowsSELECT * FROM users;
-- Translates to MongoDB find operation-- db.users.find({})Advanced WHERE Clause Support
Section titled “Advanced WHERE Clause Support”Comparison Operators
Section titled “Comparison Operators”-- Equality and comparisonSELECT * FROM users WHERE age = 25;-- → {"age": 25}
SELECT * FROM products WHERE price > 100;-- → {"price": {"$gt": 100}}
SELECT * FROM orders WHERE created_at >= '2024-01-01';-- → {"created_at": {"$gte": "2024-01-01"}}LIKE Pattern Matching
Section titled “LIKE Pattern Matching”-- SQL LIKE patterns translate to MongoDB regexSELECT * FROM users WHERE name LIKE 'John%';-- → {"name": {"$regex": "John.*", "$options": "i"}}
SELECT * FROM products WHERE description LIKE '%wireless%';-- → {"description": {"$regex": ".*wireless.*", "$options": "i"}}
SELECT * FROM codes WHERE code LIKE 'A_B%';-- → {"code": {"$regex": "A.B.*", "$options": "i"}}Pattern Translation:
%(wildcard) →.*(regex any characters)_(single char) →.(regex single character)- Case-insensitive by default with
$options: "i" - Regex special characters are automatically escaped
IN Operator
Section titled “IN Operator”-- Multiple value matchingSELECT * FROM orders WHERE status IN ('pending', 'processing', 'shipped');-- → {"status": {"$in": ["pending", "processing", "shipped"]}}
SELECT * FROM users WHERE age IN (18, 21, 25, 30);-- → {"age": {"$in": [18, 21, 25, 30]}}OR Conditions
Section titled “OR Conditions”-- Multiple conditions with OR logicSELECT * FROM users WHERE age > 65 OR status = 'premium';-- → {"$or": [{"age": {"$gt": 65}}, {"status": "premium"}]}
SELECT * FROM products WHERE price < 10 OR category = 'clearance';-- → {"$or": [{"price": {"$lt": 10}}, {"category": "clearance"}]}BETWEEN Range Queries
Section titled “BETWEEN Range Queries”-- Range queries for numeric and date valuesSELECT * FROM products WHERE price BETWEEN 100 AND 500;-- → {"price": {"$gte": 100, "$lte": 500}}
SELECT * FROM events WHERE event_date BETWEEN '2024-01-01' AND '2024-12-31';-- → {"event_date": {"$gte": "2024-01-01", "$lte": "2024-12-31"}}NULL Handling
Section titled “NULL Handling”-- Check for missing or null fieldsSELECT * FROM users WHERE email IS NULL;-- → {"$or": [{"email": null}, {"email": {"$exists": false}}]}
SELECT * FROM profiles WHERE bio IS NOT NULL;-- → {"bio": {"$exists": true, "$ne": null}}Complex Query Examples
Section titled “Complex Query Examples”-- Combining multiple conditionsSELECT * FROM shipwrecksWHERE feature_type LIKE '%Visible%' AND depth BETWEEN 0 AND 50 AND watlev IN ('always dry', 'covers and uncovers') OR coordinates IS NOT NULL;
-- Pattern matching with range filteringSELECT * FROM productsWHERE name LIKE 'iPhone%' AND price BETWEEN 500 AND 1500 AND status != 'discontinued';
-- Multi-condition searchSELECT * FROM usersWHERE (age > 18 OR verified = true) AND email IS NOT NULL AND role IN ('admin', 'moderator', 'premium');🛠 Database Management
Section titled “🛠 Database Management”DBCrust supports MongoDB database and collection management using familiar SQL syntax.
Database Operations
Section titled “Database Operations”-- Create a new databaseCREATE DATABASE analytics;-- MongoDB creates databases implicitly when first collection is created
-- Drop an existing databaseDROP DATABASE old_database;-- Permanently removes the database and all its collections
-- Switch to a different database\c productionCollection Operations
Section titled “Collection Operations”-- Create a new collectionCREATE COLLECTION user_profiles;-- Creates an empty collection in the current database
-- Drop an existing collectionDROP COLLECTION temp_data;-- Permanently removes the collection and all its documents
-- List all collections\collectionsCollection Management Workflow
Section titled “Collection Management Workflow”-- Connect to MongoDBdbcrust mongodb://localhost:27017/myapp
-- Create a new databaseCREATE DATABASE ecommerce;
-- Switch to the new database\c ecommerce
-- Create collections for our applicationCREATE COLLECTION users;CREATE COLLECTION products;CREATE COLLECTION orders;CREATE COLLECTION reviews;
-- Verify collections were created\collections
-- Clean up test collections laterDROP COLLECTION temp_testing;📊 MongoDB-Specific Commands
Section titled “📊 MongoDB-Specific Commands”Beyond SQL translation, DBCrust provides native MongoDB commands for advanced operations.
Collection Exploration
Section titled “Collection Exploration”-- List all collections with details\collections
-- Describe collection structure and sample data\dc users
-- Get detailed database statistics\mstatsIndex Management
Section titled “Index Management”-- List all indexes in the database\dmi
-- Create an index on a field\cmi users email\cmi products name
-- Create a text index for search\cmi articles content text\cmi products description text
-- Drop an index\ddmi users email_1Text Search
Section titled “Text Search”DBCrust provides powerful text search capabilities:
-- Search for documents containing specific terms\search articles "mongodb tutorial"
-- Search across multiple fields\search products "wireless bluetooth"
-- Search with complex terms\search users "john developer senior"Text Search Features:
- Full-text search using MongoDB
$textoperator - Automatic index utilization if text indexes exist
- Multi-word search term support
- Results limited to 10 by default for performance
Advanced MongoDB Queries
Section titled “Advanced MongoDB Queries”For complex operations, use native MongoDB syntax:
-- MongoDB find with specific filter\find users {"active": true, "age": {"$gte": 18}}
-- MongoDB aggregation pipeline\aggregate orders [ {"$match": {"status": "completed"}}, {"$group": {"_id": "$user_id", "total": {"$sum": "$amount"}}}, {"$sort": {"total": -1}}, {"$limit": 10}]
-- Complex find with projection and limit\find products {"category": "electronics"} {"name": 1, "price": 1} 20🏗 Data Types and Schema Handling
Section titled “🏗 Data Types and Schema Handling”MongoDB’s flexible schema is fully supported by DBCrust with intelligent type handling.
Automatic Type Detection
Section titled “Automatic Type Detection”DBCrust automatically detects and handles MongoDB’s rich data types:
// Example MongoDB document{ "_id": ObjectId("507f1f77bcf86cd799439011"), "name": "John Doe", // String "age": 30, // Integer "salary": 75000.50, // Double "active": true, // Boolean "tags": ["developer", "senior"], // Array "profile": { // Nested Document "bio": "Software engineer", "location": "San Francisco" }, "created_at": ISODate("2024-01-15T10:30:00Z"), // Date "metadata": null // Null}Column Detection and Display
Section titled “Column Detection and Display”DBCrust samples documents to create a unified column view:
SELECT * FROM users LIMIT 3;Output:
╭─────────────────────┬────────────┬─────┬─────────────┬────────┬─────────────────┬──────────────────────┬─────────────────────╮│ _id │ name │ age │ salary │ active │ tags │ profile │ created_at │├─────────────────────┼────────────┼─────┼─────────────┼────────┼─────────────────┼──────────────────────┼─────────────────────┤│ 507f1f77bcf86cd7... │ John Doe │ 30 │ 75000.5 │ true │ ["developer"... │ {"bio":"Software"... │ 2024-01-15T10:30... ││ 507f1f88bcf86cd7... │ Jane Smith │ 28 │ 82000.0 │ true │ ["manager",... │ {"bio":"Product"... │ 2024-01-14T15:22... ││ 507f1f99bcf86cd7... │ Bob Wilson │ 35 │ 68000.0 │ false │ [] │ {} │ 2024-01-13T09:15... │╰─────────────────────┴────────────┴─────┴─────────────┴────────┴─────────────────┴──────────────────────┴─────────────────────╯Handling Missing Fields
Section titled “Handling Missing Fields”MongoDB’s flexible schema means documents may have different fields:
-- Query handles documents with missing fields gracefullySELECT name, email, phone FROM users;-- Shows empty string for missing fields🔧 Advanced Features
Section titled “🔧 Advanced Features”ObjectId Handling
Section titled “ObjectId Handling”DBCrust automatically handles MongoDB ObjectIds:
-- Query by ObjectId (automatically detected and converted)SELECT * FROM users WHERE _id = '507f1f77bcf86cd799439011';-- → {"_id": ObjectId("507f1f77bcf86cd799439011")}
-- ObjectIds display as hex strings for readabilityArray and Nested Document Querying
Section titled “Array and Nested Document Querying”-- Query array fieldsSELECT * FROM users WHERE tags IN ('developer', 'senior');-- Works with MongoDB array matching
-- Query nested document fields (use dot notation in native MongoDB commands)\find users {"profile.location": "San Francisco"}Performance Optimization
Section titled “Performance Optimization”Index Usage
Section titled “Index Usage”-- Create indexes for better query performance\cmi users email\cmi orders user_id\cmi products {"name": 1, "category": 1} -- Compound index
-- Create text indexes for search\cmi articles content textQuery Limits
Section titled “Query Limits”-- Always use LIMIT for large collectionsSELECT * FROM large_collection LIMIT 100;
-- Default limits are applied automatically for safety🐳 Docker Integration
Section titled “🐳 Docker Integration”DBCrust seamlessly integrates with MongoDB Docker containers:
Container Discovery
Section titled “Container Discovery”# Interactive container selectiondbcrust docker://
# Expected output:# Available database containers:# 1. postgres-dev (postgres:13) - Port 5432 → 5433# 2. mysql-test (mysql:8.0) - Port 3306 → 3307# 3. mongodb-cache (mongo:7) - Port 27017 → 27018# 4. clickhouse-analytics (clickhouse:latest) - Port 8123 → 8124## Select container (1-4): 3Supported MongoDB Images
Section titled “Supported MongoDB Images”DBCrust automatically detects these MongoDB container images:
mongo(official MongoDB)mongodb(alternative official)bitnami/mongodb(Bitnami MongoDB)- Any image containing “mongo” in the name
Docker Environment Variables
Section titled “Docker Environment Variables”DBCrust reads standard MongoDB Docker environment variables:
| Variable | Purpose | Example |
|---|---|---|
MONGO_INITDB_ROOT_USERNAME | Root username | admin |
MONGO_INITDB_ROOT_PASSWORD | Root password | secret123 |
MONGO_INITDB_DATABASE | Initial database | myapp |
🔒 Authentication and Security
Section titled “🔒 Authentication and Security”Connection String Authentication
Section titled “Connection String Authentication”# Basic authenticationdbcrust mongodb://user:password@localhost:27017/myapp
# Authentication database specificationdbcrust mongodb://user:pass@localhost:27017/myapp?authSource=admin
# SSL/TLS connectiondbcrust mongodb://user:pass@localhost:27017/myapp?ssl=trueSession-based Security
Section titled “Session-based Security”# Save secure production connectiondbcrust mongodb+srv://user:pass@cluster.mongodb.net/prod\ss mongo_production
# Reconnect without exposing credentialsdbcrust session://mongo_production🚨 Troubleshooting
Section titled “🚨 Troubleshooting”Common Connection Issues
Section titled “Common Connection Issues”Connection Refused
Section titled “Connection Refused”# Error: Connection refused# Solution: Check if MongoDB is runningdocker ps | grep mongomongosh --eval "db.adminCommand('ping')"Authentication Failed
Section titled “Authentication Failed”# Error: Authentication failed# Solutions:# 1. Check credentialsdbcrust mongodb://correct_user:correct_pass@localhost:27017/myapp
# 2. Specify authentication databasedbcrust mongodb://user:pass@localhost:27017/myapp?authSource=adminDatabase Not Found
Section titled “Database Not Found”-- Error: Database doesn't exist-- Solution: Create the database firstCREATE DATABASE myapp;\c myappQuery Issues
Section titled “Query Issues”Empty Results
Section titled “Empty Results”-- If queries return no results, check:-- 1. Collection exists\collections
-- 2. Collection has dataSELECT COUNT(*) FROM users;
-- 3. Query conditions are correctSELECT * FROM users LIMIT 5;Performance Issues
Section titled “Performance Issues”-- For slow queries:-- 1. Check if indexes exist\dmi
-- 2. Create appropriate indexes\cmi users email\cmi orders user_id
-- 3. Use LIMIT for large result setsSELECT * FROM large_collection LIMIT 100;📋 Best Practices
Section titled “📋 Best Practices”Query Optimization
Section titled “Query Optimization”-
Always use LIMIT for exploratory queries:
SELECT * FROM users LIMIT 10; -
Create indexes for frequently queried fields:
\cmi users email\cmi orders {"user_id": 1, "created_at": -1} -
Use specific field selection when possible:
SELECT name, email FROM users WHERE active = true;
Database Design
Section titled “Database Design”-
Use meaningful collection names:
CREATE COLLECTION user_profiles; -- GoodCREATE COLLECTION data; -- Bad -
Create appropriate indexes early:
CREATE COLLECTION users;\cmi users email\cmi users {"name": 1, "created_at": -1} -
Plan for text search needs:
CREATE COLLECTION articles;\cmi articles content text\cmi articles title text
Session Management
Section titled “Session Management”-
Save frequently used connections:
dbcrust mongodb://localhost:27017/myapp\ss local_devdbcrust mongodb+srv://user:pass@cluster.mongodb.net/prod\ss production -
Use descriptive session names:
Terminal window dbcrust session://mongo_local_dev # Gooddbcrust session://db1 # Bad
🎯 Complete Workflow Example
Section titled “🎯 Complete Workflow Example”Here’s a complete example showing MongoDB usage in DBCrust:
# 1. Connect to MongoDBdbcrust mongodb://localhost:27017/ecommerce
# 2. Explore the database\collections\mstats
# 3. Examine collection structures\dc users\dc products\dc orders
# 4. Create indexes for performance\cmi users email\cmi products name\cmi orders user_id\cmi products description text
# 5. Query with advanced filteringSELECT * FROM usersWHERE email LIKE '%@company.com' AND active = true AND role IN ('admin', 'manager')LIMIT 20;
# 6. Perform text search\search products "wireless bluetooth headphones"
# 7. Use native MongoDB aggregation\aggregate orders [ {"$match": {"status": "completed"}}, {"$group": {"_id": "$product_id", "total_sales": {"$sum": "$amount"}}}, {"$sort": {"total_sales": -1}}, {"$limit": 10}]
# 8. Database managementCREATE COLLECTION user_sessions;DROP COLLECTION temp_imports;
# 9. Save session for future use\ss ecommerce_local