Core Index Operations
Indexes are critical for optimizing query performance in document-oriented databases. The following commands demonstrate fundamental index management:
Creation, Retrieval, and Removal
// Create a single-field ascending index
db.profiles.createIndex({ email: 1 });
// List all defined indexes on a collection
db.profiles.getIndexes();
// Remove a specific index definition
db.profiles.dropIndex({ email: 1 });
Compound Indexing and Prefix Matching
Multiple fields can be grouped into a single index. The numeric values dictate sort direction: 1 for ascending and -1 for descending.
db.profiles.createIndex({ status: 1, lastLogin: -1 });
Compound indexes operate on a leftmost prefix matching principle, similar to relational database systems. Queries must reference the initial field(s) of the index definition to leverage the index structure effectively.
Memory Constraints and Sorting Operations
When executing queries that require sorting, MongoDB attempts to utilize an existing index. If the target field is unindexed, the database engine must load matching documents into RAM to perform an in-memory sort. If the dataset exceeds the configured memory threshold for sorting, the operation will abort and trigger a memory limit exception.
Unique Index Constraints
Enforce data integrity by preventing duplicate values across documents:
db.accounts.createIndex({ accountNumber: 1 }, { unique: true });
Index Configuration Parameters
| Parameter | Data Type | Description |
|---|---|---|
| background | Boolean | Executes index construction asynchronously to avoid blocking concurrent database operations. Defaults to false. |
| unique | Boolean | Enforces uniqueness across the indexed field(s). Set to true to reject duplicate entries. Defaults to false. |
| name | String | Assigns a custom identifier to the index. If omitted, MongoDB auto-generates a name by concatenating field names and sort directions. |
| dropDups | Boolean | Automatically purges conflicting records when enforcing a unique constraint on existing data. Set to true to enable. Defaults to false. |
Query Execution Analysis
The explain() method reveals how the query plenner selects execution paths and processes operations.
db.users.find({ role: "moderator" }).explain();
To extract detailed performance metrics, invoke the method with verbose statistics:
db.users.find({}).explain("executionStats");
// Retrieve total execution duration: executionStats.executionTimeMillis
Authentication and Access Control
Establish Administrative Privileges
Before activating security enforcement, provision a root-level user within the administrative context.
use admin;
db.createUser({
user: "sysOpsAdmin",
pwd: "SecureP@ss2024",
roles: [ { role: "root", db: "admin" } ]
});
Enable Authorization in Daemon Configuration
Modify the database configuration file (commonly mongod.conf) to mandate credential verification.
security:
authorization: enabled
Service Restart and Client Connection
Apply configuration changes by restarting the database daemon. All subsequent connections must supply valid credentials:
// Interactive shell authentication
mongo admin -u sysOpsAdmin -p SecureP@ss2024
mongo 192.168.1.10:27017/appDb -u appUser -p userSecret
For programmatic access, embed authentication details directly into the connection URI:
const connectionString = "mongodb://sysOpsAdmin:SecureP@ss2024@127.0.0.1:27017/?authSource=admin";