{"id":990,"date":"2026-05-12T04:22:01","date_gmt":"2026-05-12T04:22:01","guid":{"rendered":"https:\/\/www.devopsschool.com\/tutorials\/?p=990"},"modified":"2026-05-12T04:22:02","modified_gmt":"2026-05-12T04:22:02","slug":"mongodb-complete-end-to-end-mongodb-tutorial-blog-from-basics-to-advanced","status":"publish","type":"post","link":"https:\/\/www.devopsschool.com\/tutorials\/mongodb-complete-end-to-end-mongodb-tutorial-blog-from-basics-to-advanced\/","title":{"rendered":"MongoDB &#8211; Complete End-to-End MongoDB Tutorial Blog: From Basics to Advanced"},"content":{"rendered":"\n<p>MongoDB is a <strong>NoSQL document database<\/strong>. Instead of storing data in rows and columns like a relational database, MongoDB stores data as <strong>documents<\/strong> inside <strong>collections<\/strong>. These documents look like JSON when you write them, but MongoDB stores them internally in a binary format called <strong>BSON<\/strong>, which supports richer data types. MongoDB is available as <strong>Community Edition<\/strong> and <strong>Enterprise Edition<\/strong>, and the official documentation provides installation paths for Linux, macOS, Windows, and Docker. (<a href=\"https:\/\/www.mongodb.com\/docs\/manual\/installation\/\">MongoDB<\/a>)<\/p>\n\n\n\n<p>This tutorial covers MongoDB from beginner to advanced level: what it is, why it is useful, how it works, architecture, installation, CRUD, indexing, aggregation, schema design, security, replication, sharding, backup, administration, and real workflows.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">1. What Is MongoDB?<\/h2>\n\n\n\n<p>MongoDB is a <strong>document-oriented database<\/strong> designed for modern applications that need flexible, scalable, high-performance data storage.<\/p>\n\n\n\n<p>In a traditional SQL database, you might store user data like this:<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table class=\"has-fixed-layout\"><thead><tr><th>id<\/th><th>name<\/th><th>email<\/th><th>city<\/th><\/tr><\/thead><tbody><tr><td>1<\/td><td>Alice<\/td><td><a href=\"mailto:alice@example.com\">alice@example.com<\/a><\/td><td>Tokyo<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p>In MongoDB, the same user is stored as a document:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>{\n  _id: ObjectId(\"...\"),\n  name: \"Alice\",\n  email: \"alice@example.com\",\n  address: {\n    city: \"Tokyo\",\n    country: \"Japan\"\n  },\n  skills: &#91;\"Linux\", \"Docker\", \"MongoDB\"]\n}\n<\/code><\/pre>\n\n\n\n<p>A MongoDB document can contain:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Strings<\/li>\n\n\n\n<li>Numbers<\/li>\n\n\n\n<li>Dates<\/li>\n\n\n\n<li>Arrays<\/li>\n\n\n\n<li>Nested objects<\/li>\n\n\n\n<li>Booleans<\/li>\n\n\n\n<li>ObjectIds<\/li>\n\n\n\n<li>Binary data<\/li>\n\n\n\n<li>Geospatial data<\/li>\n<\/ul>\n\n\n\n<p>MongoDB is popular because application data is often already object-like. For example, a user profile, product catalog item, order, blog post, or IoT event naturally fits as a document.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">2. Advantages of MongoDB<\/h2>\n\n\n\n<p>MongoDB has several major advantages.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">2.1 Flexible Schema<\/h3>\n\n\n\n<p>MongoDB does not force every document in a collection to have the exact same fields. That makes it useful when application requirements change quickly.<\/p>\n\n\n\n<p>For example:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>{\n  name: \"Laptop\",\n  price: 1200,\n  category: \"Electronics\"\n}\n<\/code><\/pre>\n\n\n\n<p>Another document in the same collection can have extra fields:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>{\n  name: \"Phone\",\n  price: 800,\n  category: \"Electronics\",\n  warranty: \"2 years\",\n  colors: &#91;\"black\", \"white\"]\n}\n<\/code><\/pre>\n\n\n\n<p>However, flexible schema does <strong>not<\/strong> mean \u201cno design.\u201d MongoDB also supports schema validation when you want to enforce data rules such as required fields, data types, or value ranges. (<a href=\"https:\/\/www.mongodb.com\/docs\/manual\/core\/schema-validation\/\">MongoDB<\/a>)<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">2.2 Natural Data Model for Applications<\/h3>\n\n\n\n<p>Most modern applications use objects, JSON, APIs, and nested data. MongoDB documents map naturally to those structures.<\/p>\n\n\n\n<p>For example, an order can store customer information and ordered items together:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>{\n  orderId: \"ORD1001\",\n  customer: {\n    name: \"Alice\",\n    email: \"alice@example.com\"\n  },\n  items: &#91;\n    { product: \"Keyboard\", qty: 1, price: 50 },\n    { product: \"Mouse\", qty: 2, price: 25 }\n  ],\n  status: \"paid\"\n}\n<\/code><\/pre>\n\n\n\n<p>This can reduce the need for joins in many use cases.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">2.3 High Availability<\/h3>\n\n\n\n<p>MongoDB supports <strong>replication<\/strong> through replica sets. A replica set is a group of <code>mongod<\/code> processes that maintain the same dataset. Replica sets provide redundancy and high availability, and MongoDB\u2019s documentation describes them as the basis for production deployments. (<a href=\"https:\/\/www.mongodb.com\/docs\/manual\/replication\/\">MongoDB<\/a>)<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">2.4 Horizontal Scalability<\/h3>\n\n\n\n<p>MongoDB supports <strong>sharding<\/strong>, which distributes data across multiple machines. A sharded cluster contains shards, <code>mongos<\/code> query routers, and config servers. Each shard stores a subset of the data and must be deployed as a replica set. (<a href=\"https:\/\/www.mongodb.com\/docs\/manual\/sharding\/\">MongoDB<\/a>)<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">2.5 Powerful Query and Aggregation System<\/h3>\n\n\n\n<p>MongoDB supports filtering, sorting, indexing, text search, geospatial queries, aggregation pipelines, and multi-document transactions. Aggregation pipelines process documents through stages such as filtering, grouping, projecting, sorting, joining, and calculating values. (<a href=\"https:\/\/www.mongodb.com\/docs\/manual\/core\/aggregation-pipeline\/\">MongoDB<\/a>)<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">2.6 Transactions<\/h3>\n\n\n\n<p>MongoDB supports multi-document transactions when you need all-or-nothing changes across multiple documents or collections. Transactions either commit all changes or roll them back. (<a href=\"https:\/\/www.mongodb.com\/docs\/manual\/core\/transactions\/\">MongoDB<\/a>)<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">3. How MongoDB Works<\/h2>\n\n\n\n<p>At a high level, MongoDB works like this:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>Application\n   |\nMongoDB Driver\n   |\nmongod or mongos\n   |\nStorage Engine\n   |\nData Files + Journal\n<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">3.1 Application Layer<\/h3>\n\n\n\n<p>Your application can be written in Node.js, Python, Java, Go, PHP, C#, Ruby, or another language. It uses a MongoDB driver to connect to the database.<\/p>\n\n\n\n<p>Example connection string:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>mongodb:\/\/localhost:27017\n<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">3.2 Driver Layer<\/h3>\n\n\n\n<p>The driver converts your application objects into MongoDB-compatible BSON documents and sends commands to the server.<\/p>\n\n\n\n<p>Example in application logic:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>await db.collection(\"users\").insertOne({\n  name: \"Alice\",\n  email: \"alice@example.com\"\n});\n<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">3.3 Server Layer: <code>mongod<\/code><\/h3>\n\n\n\n<p><code>mongod<\/code> is the main MongoDB database server process. It handles:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Client connections<\/li>\n\n\n\n<li>Reads<\/li>\n\n\n\n<li>Writes<\/li>\n\n\n\n<li>Indexes<\/li>\n\n\n\n<li>Replication<\/li>\n\n\n\n<li>Storage<\/li>\n\n\n\n<li>Query execution<\/li>\n\n\n\n<li>Authentication and authorization<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">3.4 Storage Layer<\/h3>\n\n\n\n<p>MongoDB writes data to disk through its storage engine. In modern MongoDB deployments, WiredTiger is the default storage engine. The storage layer manages data files, indexes, compression, concurrency, and journaling.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">3.5 Query Execution<\/h3>\n\n\n\n<p>When you run a query like:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>db.users.find({ email: \"alice@example.com\" })\n<\/code><\/pre>\n\n\n\n<p>MongoDB checks whether an index can help. If an appropriate index exists, MongoDB uses it to limit the number of documents scanned. Without a useful index, MongoDB may scan every document in the collection. (<a href=\"https:\/\/www.mongodb.com\/docs\/manual\/indexes\/\">MongoDB<\/a>)<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">4. MongoDB Architecture<\/h2>\n\n\n\n<p>MongoDB can run in three main deployment architectures.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h3 class=\"wp-block-heading\">4.1 Standalone Architecture<\/h3>\n\n\n\n<p>This is the simplest architecture.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>Application \u2192 mongod \u2192 Data files\n<\/code><\/pre>\n\n\n\n<p>Use it for:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Learning<\/li>\n\n\n\n<li>Local development<\/li>\n\n\n\n<li>Testing<\/li>\n\n\n\n<li>Small experiments<\/li>\n<\/ul>\n\n\n\n<p>Avoid standalone MongoDB for production because it has no automatic failover.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h3 class=\"wp-block-heading\">4.2 Replica Set Architecture<\/h3>\n\n\n\n<p>A replica set contains multiple MongoDB servers that hold the same data.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>              \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\nApplication \u2192 \u2502 Primary Node \u2502\n              \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\n                     \u2502 replication\n        \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\n        \u2193                         \u2193\n\u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510          \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\n\u2502 Secondary    \u2502          \u2502 Secondary    \u2502\n\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518          \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\n<\/code><\/pre>\n\n\n\n<p>The <strong>primary<\/strong> receives writes. The <strong>secondary<\/strong> nodes replicate data from the primary. If the primary fails, the replica set can elect a new primary.<\/p>\n\n\n\n<p>MongoDB replica sets improve:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Availability<\/li>\n\n\n\n<li>Fault tolerance<\/li>\n\n\n\n<li>Data redundancy<\/li>\n\n\n\n<li>Disaster recovery<\/li>\n\n\n\n<li>Read scaling in selected cases<\/li>\n<\/ul>\n\n\n\n<p>MongoDB documentation notes that the primary records changes in the operation log, or <strong>oplog<\/strong>, which secondaries use to replicate changes. (<a href=\"https:\/\/www.mongodb.com\/docs\/manual\/replication\/\">MongoDB<\/a>)<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h3 class=\"wp-block-heading\">4.3 Sharded Cluster Architecture<\/h3>\n\n\n\n<p>Sharding distributes data across multiple shards.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>Application\n    |\n  mongos\n    |\nConfig Servers\n    |\n \u250c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510\n \u2502 Shard 1 \u2502 Shard 2 \u2502 Shard 3 \u2502\n \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518\n<\/code><\/pre>\n\n\n\n<p>A sharded cluster contains:<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table class=\"has-fixed-layout\"><thead><tr><th>Component<\/th><th>Purpose<\/th><\/tr><\/thead><tbody><tr><td>Shard<\/td><td>Stores a subset of data<\/td><\/tr><tr><td><code>mongos<\/code><\/td><td>Query router between application and shards<\/td><\/tr><tr><td>Config servers<\/td><td>Store cluster metadata and configuration<\/td><\/tr><tr><td>Shard key<\/td><td>Field used to distribute documents<\/td><\/tr><tr><td>Balancer<\/td><td>Moves chunks to balance data<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p>Use sharding when:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>One server cannot store all data<\/li>\n\n\n\n<li>One server cannot handle all reads\/writes<\/li>\n\n\n\n<li>You need horizontal scaling<\/li>\n\n\n\n<li>You need data distribution by region or workload<\/li>\n<\/ul>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">5. MongoDB Components<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\">5.1 <code>mongod<\/code><\/h3>\n\n\n\n<p>The main database server process.<\/p>\n\n\n\n<p>Responsibilities:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Stores data<\/li>\n\n\n\n<li>Handles queries<\/li>\n\n\n\n<li>Maintains indexes<\/li>\n\n\n\n<li>Performs replication<\/li>\n\n\n\n<li>Applies access control<\/li>\n\n\n\n<li>Manages storage<\/li>\n<\/ul>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h3 class=\"wp-block-heading\">5.2 <code>mongosh<\/code><\/h3>\n\n\n\n<p><code>mongosh<\/code> is the MongoDB Shell. You use it to connect to MongoDB, run commands, query data, create users, inspect collections, and perform administration tasks. MongoDB provides separate installation guidance for <code>mongosh<\/code>. (<a href=\"https:\/\/www.mongodb.com\/docs\/mongodb-shell\/install\/\">MongoDB<\/a>)<\/p>\n\n\n\n<p>Example:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>mongosh\n<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h3 class=\"wp-block-heading\">5.3 <code>mongos<\/code><\/h3>\n\n\n\n<p><code>mongos<\/code> is the query router used in sharded clusters. Applications connect to <code>mongos<\/code>, and <code>mongos<\/code> routes operations to the correct shards.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h3 class=\"wp-block-heading\">5.4 Config Servers<\/h3>\n\n\n\n<p>Config servers store metadata for sharded clusters, including shard information and chunk distribution. In modern MongoDB sharded clusters, config servers must be deployed as a replica set. (<a href=\"https:\/\/www.mongodb.com\/docs\/manual\/sharding\/\">MongoDB<\/a>)<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h3 class=\"wp-block-heading\">5.5 MongoDB Compass<\/h3>\n\n\n\n<p>MongoDB Compass is a GUI tool for browsing databases, collections, documents, indexes, and aggregation pipelines.<\/p>\n\n\n\n<p>Use Compass when you want a visual interface instead of shell commands.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h3 class=\"wp-block-heading\">5.6 MongoDB Database Tools<\/h3>\n\n\n\n<p>MongoDB Database Tools include utilities such as:<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table class=\"has-fixed-layout\"><thead><tr><th>Tool<\/th><th>Purpose<\/th><\/tr><\/thead><tbody><tr><td><code>mongodump<\/code><\/td><td>Create binary database backups<\/td><\/tr><tr><td><code>mongorestore<\/code><\/td><td>Restore binary backups<\/td><\/tr><tr><td><code>mongoexport<\/code><\/td><td>Export data as JSON or CSV<\/td><\/tr><tr><td><code>mongoimport<\/code><\/td><td>Import JSON, CSV, or TSV<\/td><\/tr><tr><td><code>bsondump<\/code><\/td><td>Inspect BSON files<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p><code>mongodump<\/code> and <code>mongorestore<\/code> are useful for small deployments, but MongoDB documentation recommends snapshots or Atlas cloud backups for more resilient, non-disruptive backup strategies. (<a href=\"https:\/\/www.mongodb.com\/docs\/v8.0\/tutorial\/backup-and-restore-tools\/\">MongoDB<\/a>)<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">6. MongoDB Terminology<\/h2>\n\n\n\n<figure class=\"wp-block-table\"><table class=\"has-fixed-layout\"><thead><tr><th>Relational Database<\/th><th>MongoDB<\/th><\/tr><\/thead><tbody><tr><td>Database<\/td><td>Database<\/td><\/tr><tr><td>Table<\/td><td>Collection<\/td><\/tr><tr><td>Row<\/td><td>Document<\/td><\/tr><tr><td>Column<\/td><td>Field<\/td><\/tr><tr><td>Primary key<\/td><td><code>_id<\/code><\/td><\/tr><tr><td>Index<\/td><td>Index<\/td><\/tr><tr><td>Join<\/td><td><code>$lookup<\/code>, embedding, or application-side join<\/td><\/tr><tr><td>View<\/td><td>View<\/td><\/tr><tr><td>Transaction<\/td><td>Transaction<\/td><\/tr><tr><td>SQL<\/td><td>MongoDB Query Language<\/td><\/tr><tr><td>Schema<\/td><td>Flexible schema \/ schema validation<\/td><\/tr><tr><td>Server<\/td><td><code>mongod<\/code><\/td><\/tr><tr><td>Cluster router<\/td><td><code>mongos<\/code><\/td><\/tr><tr><td>Replication log<\/td><td>Oplog<\/td><\/tr><tr><td>Horizontal partitioning<\/td><td>Sharding<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">7. Installing MongoDB<\/h2>\n\n\n\n<p>For beginners, the easiest installation method is Docker. For production, use official packages for your operating system or MongoDB Atlas.<\/p>\n\n\n\n<p>MongoDB\u2019s official installation documentation covers Community and Enterprise editions across Linux, macOS, Windows, and Docker. (<a href=\"https:\/\/www.mongodb.com\/docs\/manual\/installation\/\">MongoDB<\/a>)<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h3 class=\"wp-block-heading\">7.1 Install MongoDB Using Docker<\/h3>\n\n\n\n<p>Create a MongoDB container:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>docker run -d \\\n  --name mongodb \\\n  -p 27017:27017 \\\n  -v mongodb_data:\/data\/db \\\n  mongo:8.0\n<\/code><\/pre>\n\n\n\n<p>Check container status:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>docker ps\n<\/code><\/pre>\n\n\n\n<p>Connect using <code>mongosh<\/code> inside the container:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>docker exec -it mongodb mongosh\n<\/code><\/pre>\n\n\n\n<p>Stop MongoDB:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>docker stop mongodb\n<\/code><\/pre>\n\n\n\n<p>Start it again:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>docker start mongodb\n<\/code><\/pre>\n\n\n\n<p>Remove container:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>docker rm -f mongodb\n<\/code><\/pre>\n\n\n\n<p>Remove volume:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>docker volume rm mongodb_data\n<\/code><\/pre>\n\n\n\n<p>For a beginner lab, Docker is clean because it avoids OS package conflicts.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h3 class=\"wp-block-heading\">7.2 Install MongoDB on Ubuntu<\/h3>\n\n\n\n<p>The official Ubuntu installation uses the <code>mongodb-org<\/code> package maintained by MongoDB Inc.; MongoDB warns that Ubuntu\u2019s separate <code>mongodb<\/code> package is not maintained by MongoDB Inc. and conflicts with the official package. (<a href=\"https:\/\/www.mongodb.com\/docs\/v8.0\/tutorial\/install-mongodb-on-ubuntu\/\">MongoDB<\/a>)<\/p>\n\n\n\n<p>Install prerequisites:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>sudo apt-get update\nsudo apt-get install -y gnupg curl\n<\/code><\/pre>\n\n\n\n<p>Import MongoDB public key:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>curl -fsSL https:\/\/pgp.mongodb.com\/server-8.0.asc | \\\n  sudo gpg -o \/usr\/share\/keyrings\/mongodb-server-8.0.gpg \\\n  --dearmor\n<\/code><\/pre>\n\n\n\n<p>For Ubuntu 24.04:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>echo \"deb &#91; arch=amd64,arm64 signed-by=\/usr\/share\/keyrings\/mongodb-server-8.0.gpg ] https:\/\/repo.mongodb.org\/apt\/ubuntu noble\/mongodb-org\/8.0 multiverse\" | \\\n  sudo tee \/etc\/apt\/sources.list.d\/mongodb-org-8.0.list\n<\/code><\/pre>\n\n\n\n<p>Install MongoDB:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>sudo apt-get update\nsudo apt-get install -y mongodb-org\n<\/code><\/pre>\n\n\n\n<p>Start MongoDB:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>sudo systemctl start mongod\n<\/code><\/pre>\n\n\n\n<p>Enable MongoDB at boot:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>sudo systemctl enable mongod\n<\/code><\/pre>\n\n\n\n<p>Check status:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>sudo systemctl status mongod\n<\/code><\/pre>\n\n\n\n<p>Connect:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>mongosh\n<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h3 class=\"wp-block-heading\">7.3 Install MongoDB on macOS<\/h3>\n\n\n\n<p>MongoDB\u2019s macOS Community Edition documentation is based on Homebrew and covers MongoDB 8.0 Community Edition. (<a href=\"https:\/\/www.mongodb.com\/docs\/v8.0\/tutorial\/install-mongodb-on-os-x\/\">MongoDB<\/a>)<\/p>\n\n\n\n<p>Install Homebrew if needed, then run:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>brew tap mongodb\/brew\nbrew install mongodb-community@8.0\n<\/code><\/pre>\n\n\n\n<p>Start MongoDB:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>brew services start mongodb-community@8.0\n<\/code><\/pre>\n\n\n\n<p>Stop MongoDB:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>brew services stop mongodb-community@8.0\n<\/code><\/pre>\n\n\n\n<p>Connect:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>mongosh\n<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h3 class=\"wp-block-heading\">7.4 Install MongoDB on Windows<\/h3>\n\n\n\n<p>MongoDB\u2019s Windows Community Edition documentation uses the MSI installer by default, and notes that <code>mongosh<\/code> is not installed with MongoDB Server. (<a href=\"https:\/\/www.mongodb.com\/docs\/v8.0\/tutorial\/install-mongodb-on-windows\/\">MongoDB<\/a>)<\/p>\n\n\n\n<p>Typical Windows workflow:<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li>Download MongoDB Community Server MSI.<\/li>\n\n\n\n<li>Run the installer.<\/li>\n\n\n\n<li>Choose \u201cComplete\u201d setup.<\/li>\n\n\n\n<li>Install MongoDB as a Windows service.<\/li>\n\n\n\n<li>Install MongoDB Compass if desired.<\/li>\n\n\n\n<li>Install <code>mongosh<\/code> separately if it is not included.<\/li>\n\n\n\n<li>Open PowerShell or Command Prompt.<\/li>\n\n\n\n<li>Run:<\/li>\n<\/ol>\n\n\n\n<pre class=\"wp-block-code\"><code>mongosh\n<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">8. Getting Started with MongoDB<\/h2>\n\n\n\n<p>Start <code>mongosh<\/code>:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>mongosh\n<\/code><\/pre>\n\n\n\n<p>Show databases:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>show dbs\n<\/code><\/pre>\n\n\n\n<p>Create or switch to a database:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>use bookstore\n<\/code><\/pre>\n\n\n\n<p>MongoDB creates the database only after you insert data.<\/p>\n\n\n\n<p>Create a collection:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>db.createCollection(\"books\")\n<\/code><\/pre>\n\n\n\n<p>Show collections:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>show collections\n<\/code><\/pre>\n\n\n\n<p>Insert one document:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>db.books.insertOne({\n  title: \"MongoDB Basics\",\n  author: \"Alice Tanaka\",\n  price: 29.99,\n  category: \"Database\",\n  publishedYear: 2026,\n  tags: &#91;\"mongodb\", \"nosql\", \"database\"],\n  stock: 50,\n  createdAt: new Date()\n})\n<\/code><\/pre>\n\n\n\n<p>Insert many documents:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>db.books.insertMany(&#91;\n  {\n    title: \"Linux for DevOps\",\n    author: \"Ken Sato\",\n    price: 34.99,\n    category: \"DevOps\",\n    publishedYear: 2025,\n    tags: &#91;\"linux\", \"devops\"],\n    stock: 30,\n    createdAt: new Date()\n  },\n  {\n    title: \"Docker Practical Guide\",\n    author: \"Maria Silva\",\n    price: 39.99,\n    category: \"Containers\",\n    publishedYear: 2026,\n    tags: &#91;\"docker\", \"containers\"],\n    stock: 20,\n    createdAt: new Date()\n  }\n])\n<\/code><\/pre>\n\n\n\n<p>Find all documents:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>db.books.find()\n<\/code><\/pre>\n\n\n\n<p>Pretty print:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>db.books.find().pretty()\n<\/code><\/pre>\n\n\n\n<p>Find one document:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>db.books.findOne({ title: \"MongoDB Basics\" })\n<\/code><\/pre>\n\n\n\n<p>Filter documents:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>db.books.find({ category: \"Database\" })\n<\/code><\/pre>\n\n\n\n<p>Use comparison operators:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>db.books.find({ price: { $gt: 30 } })\n<\/code><\/pre>\n\n\n\n<p>Use logical operators:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>db.books.find({\n  $and: &#91;\n    { price: { $gt: 20 } },\n    { stock: { $gt: 10 } }\n  ]\n})\n<\/code><\/pre>\n\n\n\n<p>Find by array value:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>db.books.find({ tags: \"docker\" })\n<\/code><\/pre>\n\n\n\n<p>Projection: return selected fields only:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>db.books.find(\n  { category: \"Database\" },\n  { title: 1, author: 1, price: 1, _id: 0 }\n)\n<\/code><\/pre>\n\n\n\n<p>Sort results:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>db.books.find().sort({ price: 1 })\n<\/code><\/pre>\n\n\n\n<p>Limit results:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>db.books.find().limit(2)\n<\/code><\/pre>\n\n\n\n<p>Skip results:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>db.books.find().skip(2).limit(2)\n<\/code><\/pre>\n\n\n\n<p>Update one document:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>db.books.updateOne(\n  { title: \"MongoDB Basics\" },\n  { $set: { price: 24.99 } }\n)\n<\/code><\/pre>\n\n\n\n<p>Update many documents:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>db.books.updateMany(\n  { category: \"Database\" },\n  { $inc: { stock: 10 } }\n)\n<\/code><\/pre>\n\n\n\n<p>Add value to array:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>db.books.updateOne(\n  { title: \"MongoDB Basics\" },\n  { $addToSet: { tags: \"beginner\" } }\n)\n<\/code><\/pre>\n\n\n\n<p>Delete one document:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>db.books.deleteOne({ title: \"Docker Practical Guide\" })\n<\/code><\/pre>\n\n\n\n<p>Delete many documents:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>db.books.deleteMany({ stock: { $lte: 0 } })\n<\/code><\/pre>\n\n\n\n<p>Drop collection:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>db.books.drop()\n<\/code><\/pre>\n\n\n\n<p>Drop database:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>db.dropDatabase()\n<\/code><\/pre>\n\n\n\n<p>MongoDB CRUD operations are create, read, update, and delete operations on documents. (<a href=\"https:\/\/www.mongodb.com\/docs\/manual\/crud\/\">MongoDB<\/a>)<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">9. MongoDB Data Modeling<\/h2>\n\n\n\n<p>MongoDB data modeling is one of the most important skills.<\/p>\n\n\n\n<p>You usually choose between:<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Embedding<\/strong><\/li>\n\n\n\n<li><strong>Referencing<\/strong><\/li>\n<\/ol>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h3 class=\"wp-block-heading\">9.1 Embedding<\/h3>\n\n\n\n<p>Embedding means storing related data inside the same document.<\/p>\n\n\n\n<p>Example:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>{\n  title: \"MongoDB Basics\",\n  author: \"Alice Tanaka\",\n  reviews: &#91;\n    {\n      user: \"Ravi\",\n      rating: 5,\n      comment: \"Very helpful\"\n    },\n    {\n      user: \"Yuki\",\n      rating: 4,\n      comment: \"Good beginner guide\"\n    }\n  ]\n}\n<\/code><\/pre>\n\n\n\n<p>Use embedding when:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Data is frequently read together<\/li>\n\n\n\n<li>Child data belongs strongly to parent data<\/li>\n\n\n\n<li>Child data is limited in size<\/li>\n\n\n\n<li>You want fast reads<\/li>\n<\/ul>\n\n\n\n<p>Good examples:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Blog post with comments<\/li>\n\n\n\n<li>Order with order items<\/li>\n\n\n\n<li>User profile with address<\/li>\n\n\n\n<li>Product with attributes<\/li>\n<\/ul>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h3 class=\"wp-block-heading\">9.2 Referencing<\/h3>\n\n\n\n<p>Referencing means storing related data in separate collections and linking by <code>_id<\/code>.<\/p>\n\n\n\n<p>Users:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>{\n  _id: ObjectId(\"64...\"),\n  name: \"Alice\"\n}\n<\/code><\/pre>\n\n\n\n<p>Orders:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>{\n  _id: ObjectId(\"65...\"),\n  userId: ObjectId(\"64...\"),\n  total: 150\n}\n<\/code><\/pre>\n\n\n\n<p>Use referencing when:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Related data is large<\/li>\n\n\n\n<li>Related data changes frequently<\/li>\n\n\n\n<li>Many documents share the same related data<\/li>\n\n\n\n<li>You need many-to-many relationships<\/li>\n<\/ul>\n\n\n\n<p>Good examples:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Users and roles<\/li>\n\n\n\n<li>Products and categories<\/li>\n\n\n\n<li>Students and courses<\/li>\n\n\n\n<li>Authors and books<\/li>\n<\/ul>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h3 class=\"wp-block-heading\">9.3 Rule of Thumb<\/h3>\n\n\n\n<p>Use embedding when data is \u201cowned by\u201d the parent and read together.<\/p>\n\n\n\n<p>Use referencing when data is independent, large, shared, or frequently updated.<\/p>\n\n\n\n<p>Tiny hot take: MongoDB schema design is not \u201cno schema.\u201d It is \u201cput the schema where it actually helps.\u201d Sometimes that is the application. Sometimes that is validation. Sometimes it is both.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">10. Schema Validation<\/h2>\n\n\n\n<p>MongoDB allows flexible documents by default, but you can enforce rules using schema validation. Schema validation can check required fields, data types, value ranges, and document shape. (<a href=\"https:\/\/www.mongodb.com\/docs\/manual\/core\/schema-validation\/\">MongoDB<\/a>)<\/p>\n\n\n\n<p>Create a collection with validation:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>db.createCollection(\"students\", {\n  validator: {\n    $jsonSchema: {\n      bsonType: \"object\",\n      required: &#91;\"name\", \"email\", \"age\"],\n      properties: {\n        name: {\n          bsonType: \"string\",\n          description: \"Name must be a string\"\n        },\n        email: {\n          bsonType: \"string\",\n          pattern: \"^.+@.+\\\\..+$\",\n          description: \"Email must be valid\"\n        },\n        age: {\n          bsonType: \"int\",\n          minimum: 18,\n          maximum: 100,\n          description: \"Age must be between 18 and 100\"\n        }\n      }\n    }\n  }\n})\n<\/code><\/pre>\n\n\n\n<p>Valid insert:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>db.students.insertOne({\n  name: \"Aiko\",\n  email: \"aiko@example.com\",\n  age: 22\n})\n<\/code><\/pre>\n\n\n\n<p>Invalid insert:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>db.students.insertOne({\n  name: \"Aiko\",\n  age: 15\n})\n<\/code><\/pre>\n\n\n\n<p>The invalid insert fails because <code>email<\/code> is missing and <code>age<\/code> is below the allowed minimum.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">11. Indexes in MongoDB<\/h2>\n\n\n\n<p>Indexes make queries faster. Without an index, MongoDB may scan every document in a collection. With a suitable index, MongoDB can scan fewer documents. Indexes improve query performance but add write overhead because inserts and updates must also update indexes. (<a href=\"https:\/\/www.mongodb.com\/docs\/manual\/indexes\/\">MongoDB<\/a>)<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h3 class=\"wp-block-heading\">11.1 Create a Single-Field Index<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>db.books.createIndex({ title: 1 })\n<\/code><\/pre>\n\n\n\n<p><code>1<\/code> means ascending order. <code>-1<\/code> means descending order.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h3 class=\"wp-block-heading\">11.2 Create a Unique Index<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>db.users.createIndex({ email: 1 }, { unique: true })\n<\/code><\/pre>\n\n\n\n<p>Now duplicate emails are rejected.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h3 class=\"wp-block-heading\">11.3 Create a Compound Index<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>db.books.createIndex({ category: 1, price: -1 })\n<\/code><\/pre>\n\n\n\n<p>Useful query:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>db.books.find({ category: \"Database\" }).sort({ price: -1 })\n<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h3 class=\"wp-block-heading\">11.4 List Indexes<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>db.books.getIndexes()\n<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h3 class=\"wp-block-heading\">11.5 Drop Index<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>db.books.dropIndex({ title: 1 })\n<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h3 class=\"wp-block-heading\">11.6 Use <code>explain()<\/code><\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>db.books.find({ title: \"MongoDB Basics\" }).explain(\"executionStats\")\n<\/code><\/pre>\n\n\n\n<p>Look for:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><code>COLLSCAN<\/code>: collection scan, usually bad for large collections<\/li>\n\n\n\n<li><code>IXSCAN<\/code>: index scan, usually better<\/li>\n\n\n\n<li><code>totalDocsExamined<\/code><\/li>\n\n\n\n<li><code>totalKeysExamined<\/code><\/li>\n\n\n\n<li><code>executionTimeMillis<\/code><\/li>\n<\/ul>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h3 class=\"wp-block-heading\">11.7 Index Best Practices<\/h3>\n\n\n\n<p>Create indexes for:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Frequent filters<\/li>\n\n\n\n<li>Frequent sorts<\/li>\n\n\n\n<li>Unique fields<\/li>\n\n\n\n<li>Foreign-key-like reference fields<\/li>\n\n\n\n<li>Common search patterns<\/li>\n<\/ul>\n\n\n\n<p>Avoid:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Too many indexes<\/li>\n\n\n\n<li>Indexing low-value fields unnecessarily<\/li>\n\n\n\n<li>Creating indexes without checking query patterns<\/li>\n\n\n\n<li>Ignoring write overhead<\/li>\n<\/ul>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">12. Aggregation Pipeline<\/h2>\n\n\n\n<p>Aggregation is MongoDB\u2019s data processing framework. It works like a pipeline: documents pass through stages, and each stage transforms, filters, groups, sorts, joins, or calculates data. MongoDB documentation notes that aggregation stages pass output documents to the next stage, and aggregation can return grouped results. (<a href=\"https:\/\/www.mongodb.com\/docs\/manual\/core\/aggregation-pipeline\/\">MongoDB<\/a>)<\/p>\n\n\n\n<p>Basic structure:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>db.collection.aggregate(&#91;\n  { stage1 },\n  { stage2 },\n  { stage3 }\n])\n<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h3 class=\"wp-block-heading\">12.1 Sample Data<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>db.orders.insertMany(&#91;\n  {\n    customer: \"Alice\",\n    status: \"paid\",\n    total: 120,\n    items: &#91;\n      { product: \"Keyboard\", qty: 1, price: 50 },\n      { product: \"Mouse\", qty: 2, price: 35 }\n    ],\n    createdAt: new Date(\"2026-01-10\")\n  },\n  {\n    customer: \"Bob\",\n    status: \"pending\",\n    total: 80,\n    items: &#91;\n      { product: \"Mouse\", qty: 2, price: 40 }\n    ],\n    createdAt: new Date(\"2026-01-11\")\n  },\n  {\n    customer: \"Alice\",\n    status: \"paid\",\n    total: 200,\n    items: &#91;\n      { product: \"Monitor\", qty: 1, price: 200 }\n    ],\n    createdAt: new Date(\"2026-01-12\")\n  }\n])\n<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h3 class=\"wp-block-heading\">12.2 <code>$match<\/code><\/h3>\n\n\n\n<p>Filters documents.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>db.orders.aggregate(&#91;\n  { $match: { status: \"paid\" } }\n])\n<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h3 class=\"wp-block-heading\">12.3 <code>$group<\/code><\/h3>\n\n\n\n<p>Groups documents and calculates values.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>db.orders.aggregate(&#91;\n  { $match: { status: \"paid\" } },\n  {\n    $group: {\n      _id: \"$customer\",\n      totalSpent: { $sum: \"$total\" },\n      orderCount: { $sum: 1 }\n    }\n  }\n])\n<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h3 class=\"wp-block-heading\">12.4 <code>$project<\/code><\/h3>\n\n\n\n<p>Controls output fields.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>db.orders.aggregate(&#91;\n  {\n    $project: {\n      customer: 1,\n      total: 1,\n      tax: { $multiply: &#91;\"$total\", 0.1] },\n      grandTotal: { $multiply: &#91;\"$total\", 1.1] }\n    }\n  }\n])\n<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h3 class=\"wp-block-heading\">12.5 <code>$sort<\/code><\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>db.orders.aggregate(&#91;\n  { $sort: { total: -1 } }\n])\n<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h3 class=\"wp-block-heading\">12.6 <code>$unwind<\/code><\/h3>\n\n\n\n<p>Breaks array items into separate documents.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>db.orders.aggregate(&#91;\n  { $unwind: \"$items\" },\n  {\n    $group: {\n      _id: \"$items.product\",\n      totalQuantity: { $sum: \"$items.qty\" },\n      totalRevenue: {\n        $sum: { $multiply: &#91;\"$items.qty\", \"$items.price\"] }\n      }\n    }\n  }\n])\n<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h3 class=\"wp-block-heading\">12.7 <code>$lookup<\/code><\/h3>\n\n\n\n<p>Performs a left outer join between collections.<\/p>\n\n\n\n<p>Products:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>db.products.insertMany(&#91;\n  { _id: 1, name: \"Keyboard\", category: \"Accessories\" },\n  { _id: 2, name: \"Mouse\", category: \"Accessories\" }\n])\n<\/code><\/pre>\n\n\n\n<p>Order items:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>db.orderItems.insertMany(&#91;\n  { orderId: 101, productId: 1, qty: 1 },\n  { orderId: 102, productId: 2, qty: 2 }\n])\n<\/code><\/pre>\n\n\n\n<p>Join:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>db.orderItems.aggregate(&#91;\n  {\n    $lookup: {\n      from: \"products\",\n      localField: \"productId\",\n      foreignField: \"_id\",\n      as: \"productDetails\"\n    }\n  }\n])\n<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">13. Transactions<\/h2>\n\n\n\n<p>MongoDB supports multi-document transactions for use cases where multiple changes must succeed or fail together. The official docs describe distributed transactions as atomic: changes are applied together or rolled back. (<a href=\"https:\/\/www.mongodb.com\/docs\/manual\/core\/transactions\/\">MongoDB<\/a>)<\/p>\n\n\n\n<p>Example use case:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Deduct money from one account<\/li>\n\n\n\n<li>Add money to another account<\/li>\n\n\n\n<li>Record transfer history<\/li>\n<\/ul>\n\n\n\n<p>If one step fails, all changes should be rolled back.<\/p>\n\n\n\n<p>Example structure in JavaScript-style pseudocode:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>const session = client.startSession();\n\ntry {\n  session.startTransaction();\n\n  await accounts.updateOne(\n    { accountNo: \"A100\" },\n    { $inc: { balance: -100 } },\n    { session }\n  );\n\n  await accounts.updateOne(\n    { accountNo: \"B200\" },\n    { $inc: { balance: 100 } },\n    { session }\n  );\n\n  await transfers.insertOne(\n    {\n      from: \"A100\",\n      to: \"B200\",\n      amount: 100,\n      createdAt: new Date()\n    },\n    { session }\n  );\n\n  await session.commitTransaction();\n} catch (error) {\n  await session.abortTransaction();\n} finally {\n  await session.endSession();\n}\n<\/code><\/pre>\n\n\n\n<p>Use transactions when you truly need them. Do not use transactions to hide poor schema design. In MongoDB, good document design often reduces the need for multi-document transactions.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">14. Security: Authentication and Authorization<\/h2>\n\n\n\n<p>MongoDB security has two major parts:<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table class=\"has-fixed-layout\"><thead><tr><th>Concept<\/th><th>Meaning<\/th><\/tr><\/thead><tbody><tr><td>Authentication<\/td><td>Proves who the user is<\/td><\/tr><tr><td>Authorization<\/td><td>Controls what the user can do<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p>MongoDB documentation explains that authentication verifies identity, while authorization determines access to resources and operations. (<a href=\"https:\/\/www.mongodb.com\/docs\/manual\/core\/authentication\/\">MongoDB<\/a>)<\/p>\n\n\n\n<p>MongoDB uses Role-Based Access Control. A user is granted one or more roles, and outside those roles, the user has no access. Access control is not enabled by default in self-managed deployments. (<a href=\"https:\/\/www.mongodb.com\/docs\/manual\/core\/authorization\/\">MongoDB<\/a>)<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h3 class=\"wp-block-heading\">14.1 Create Admin User<\/h3>\n\n\n\n<p>Connect locally before enabling auth:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>mongosh\n<\/code><\/pre>\n\n\n\n<p>Switch to admin database:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>use admin\n<\/code><\/pre>\n\n\n\n<p>Create admin user:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>db.createUser({\n  user: \"adminUser\",\n  pwd: passwordPrompt(),\n  roles: &#91;\n    { role: \"userAdminAnyDatabase\", db: \"admin\" },\n    { role: \"readWriteAnyDatabase\", db: \"admin\" },\n    { role: \"dbAdminAnyDatabase\", db: \"admin\" }\n  ]\n})\n<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h3 class=\"wp-block-heading\">14.2 Enable Authorization<\/h3>\n\n\n\n<p>Edit MongoDB config file:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>sudo nano \/etc\/mongod.conf\n<\/code><\/pre>\n\n\n\n<p>Add:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>security:\n  authorization: enabled\n<\/code><\/pre>\n\n\n\n<p>Restart MongoDB:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>sudo systemctl restart mongod\n<\/code><\/pre>\n\n\n\n<p>Connect with authentication:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>mongosh -u adminUser -p --authenticationDatabase admin\n<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h3 class=\"wp-block-heading\">14.3 Create Application User<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>use bookstore\n\ndb.createUser({\n  user: \"bookAppUser\",\n  pwd: passwordPrompt(),\n  roles: &#91;\n    { role: \"readWrite\", db: \"bookstore\" }\n  ]\n})\n<\/code><\/pre>\n\n\n\n<p>Connect as app user:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>mongosh -u bookAppUser -p --authenticationDatabase bookstore\n<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h3 class=\"wp-block-heading\">14.4 Common Built-In Roles<\/h3>\n\n\n\n<figure class=\"wp-block-table\"><table class=\"has-fixed-layout\"><thead><tr><th>Role<\/th><th>Purpose<\/th><\/tr><\/thead><tbody><tr><td><code>read<\/code><\/td><td>Read-only access<\/td><\/tr><tr><td><code>readWrite<\/code><\/td><td>Read and write access<\/td><\/tr><tr><td><code>dbAdmin<\/code><\/td><td>Database administration<\/td><\/tr><tr><td><code>userAdmin<\/code><\/td><td>User management for one database<\/td><\/tr><tr><td><code>userAdminAnyDatabase<\/code><\/td><td>User management across databases<\/td><\/tr><tr><td><code>readWriteAnyDatabase<\/code><\/td><td>Read\/write across databases<\/td><\/tr><tr><td><code>clusterAdmin<\/code><\/td><td>Cluster administration<\/td><\/tr><tr><td><code>backup<\/code><\/td><td>Backup privileges<\/td><\/tr><tr><td><code>restore<\/code><\/td><td>Restore privileges<\/td><\/tr><tr><td><code>root<\/code><\/td><td>Superuser role<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">15. Replication: High Availability<\/h2>\n\n\n\n<p>A replica set is the standard production pattern for MongoDB. It contains multiple <code>mongod<\/code> instances with the same data. MongoDB\u2019s documentation states that replica sets provide redundancy and high availability. (<a href=\"https:\/\/www.mongodb.com\/docs\/manual\/replication\/\">MongoDB<\/a>)<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h3 class=\"wp-block-heading\">15.1 Replica Set Components<\/h3>\n\n\n\n<figure class=\"wp-block-table\"><table class=\"has-fixed-layout\"><thead><tr><th>Component<\/th><th>Meaning<\/th><\/tr><\/thead><tbody><tr><td>Primary<\/td><td>Accepts writes<\/td><\/tr><tr><td>Secondary<\/td><td>Replicates from primary<\/td><\/tr><tr><td>Arbiter<\/td><td>Votes in elections but does not store data<\/td><\/tr><tr><td>Oplog<\/td><td>Operation log used for replication<\/td><\/tr><tr><td>Election<\/td><td>Process of choosing a new primary<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h3 class=\"wp-block-heading\">15.2 Local Replica Set with Docker Compose<\/h3>\n\n\n\n<p>Create <code>docker-compose.yml<\/code>:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>services:\n  mongo1:\n    image: mongo:8.0\n    container_name: mongo1\n    command: &#91;\"mongod\", \"--replSet\", \"rs0\", \"--bind_ip_all\"]\n    ports:\n      - \"27017:27017\"\n    volumes:\n      - mongo1_data:\/data\/db\n\n  mongo2:\n    image: mongo:8.0\n    container_name: mongo2\n    command: &#91;\"mongod\", \"--replSet\", \"rs0\", \"--bind_ip_all\"]\n    ports:\n      - \"27018:27017\"\n    volumes:\n      - mongo2_data:\/data\/db\n\n  mongo3:\n    image: mongo:8.0\n    container_name: mongo3\n    command: &#91;\"mongod\", \"--replSet\", \"rs0\", \"--bind_ip_all\"]\n    ports:\n      - \"27019:27017\"\n    volumes:\n      - mongo3_data:\/data\/db\n\nvolumes:\n  mongo1_data:\n  mongo2_data:\n  mongo3_data:\n<\/code><\/pre>\n\n\n\n<p>Start:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>docker compose up -d\n<\/code><\/pre>\n\n\n\n<p>Connect to first node:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>docker exec -it mongo1 mongosh\n<\/code><\/pre>\n\n\n\n<p>Initialize replica set:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>rs.initiate({\n  _id: \"rs0\",\n  members: &#91;\n    { _id: 0, host: \"mongo1:27017\" },\n    { _id: 1, host: \"mongo2:27017\" },\n    { _id: 2, host: \"mongo3:27017\" }\n  ]\n})\n<\/code><\/pre>\n\n\n\n<p>Check status:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>rs.status()\n<\/code><\/pre>\n\n\n\n<p>Check primary:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>rs.isMaster()\n<\/code><\/pre>\n\n\n\n<p>Insert data:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>use replab\ndb.test.insertOne({ message: \"replication works\", createdAt: new Date() })\n<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">16. Sharding: Horizontal Scaling<\/h2>\n\n\n\n<p>Sharding is MongoDB\u2019s horizontal scaling system. It distributes collection data across multiple shards. MongoDB sharded clusters include shards, <code>mongos<\/code> routers, and config servers. (<a href=\"https:\/\/www.mongodb.com\/docs\/manual\/sharding\/\">MongoDB<\/a>)<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h3 class=\"wp-block-heading\">16.1 When to Use Sharding<\/h3>\n\n\n\n<p>Use sharding when:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Data is too large for one server<\/li>\n\n\n\n<li>Write throughput is too high for one server<\/li>\n\n\n\n<li>Working set does not fit on one machine<\/li>\n\n\n\n<li>You need regional data distribution<\/li>\n\n\n\n<li>You need very large-scale growth<\/li>\n<\/ul>\n\n\n\n<p>Do <strong>not<\/strong> start with sharding unless you need it. Most applications should start with a replica set.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h3 class=\"wp-block-heading\">16.2 Shard Key<\/h3>\n\n\n\n<p>A shard key determines how MongoDB distributes data.<\/p>\n\n\n\n<p>Good shard key characteristics:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>High cardinality<\/li>\n\n\n\n<li>Even distribution<\/li>\n\n\n\n<li>Supports common queries<\/li>\n\n\n\n<li>Avoids hot spots<\/li>\n\n\n\n<li>Does not constantly increase in one direction unless handled carefully<\/li>\n<\/ul>\n\n\n\n<p>Poor shard key examples:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>{ status: 1 }\n<\/code><\/pre>\n\n\n\n<p>Bad because <code>status<\/code> may only have a few values.<\/p>\n\n\n\n<p>Potentially risky:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>{ createdAt: 1 }\n<\/code><\/pre>\n\n\n\n<p>Can create hot spots if inserts always go to the newest range.<\/p>\n\n\n\n<p>Better example:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>{ customerId: 1, orderId: 1 }\n<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h3 class=\"wp-block-heading\">16.3 Sharding Commands: Conceptual Example<\/h3>\n\n\n\n<p>Enable sharding on database:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>sh.enableSharding(\"shop\")\n<\/code><\/pre>\n\n\n\n<p>Create index on shard key:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>db.orders.createIndex({ customerId: 1, orderId: 1 })\n<\/code><\/pre>\n\n\n\n<p>Shard collection:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>sh.shardCollection(\"shop.orders\", { customerId: 1, orderId: 1 })\n<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">17. Backup and Restore<\/h2>\n\n\n\n<p>Backups are non-negotiable. A database without tested backups is basically a suspense movie with invoices.<\/p>\n\n\n\n<p>MongoDB\u2019s backup and restore tools include <code>mongodump<\/code> and <code>mongorestore<\/code>. These create and restore BSON data dumps. Official documentation says they are useful for small deployments, but they can affect performance because they read data through a running MongoDB instance. MongoDB recommends verifying backups by restoring them to a test deployment. (<a href=\"https:\/\/www.mongodb.com\/docs\/v8.0\/tutorial\/backup-and-restore-tools\/\">MongoDB<\/a>)<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h3 class=\"wp-block-heading\">17.1 Backup a Database<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>mongodump --db bookstore --out \/backup\/mongodb\n<\/code><\/pre>\n\n\n\n<p>Backup with authentication:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>mongodump \\\n  --username adminUser \\\n  --password \\\n  --authenticationDatabase admin \\\n  --db bookstore \\\n  --out \/backup\/mongodb\n<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h3 class=\"wp-block-heading\">17.2 Restore a Database<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>mongorestore --db bookstore \/backup\/mongodb\/bookstore\n<\/code><\/pre>\n\n\n\n<p>Restore with authentication:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>mongorestore \\\n  --username adminUser \\\n  --password \\\n  --authenticationDatabase admin \\\n  --db bookstore \\\n  \/backup\/mongodb\/bookstore\n<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h3 class=\"wp-block-heading\">17.3 Backup Best Practices<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Automate backups<\/li>\n\n\n\n<li>Store backups off-server<\/li>\n\n\n\n<li>Encrypt backups<\/li>\n\n\n\n<li>Test restore regularly<\/li>\n\n\n\n<li>Label backups with date and database name<\/li>\n\n\n\n<li>Monitor backup success and failure<\/li>\n\n\n\n<li>For production, prefer snapshot-based or managed cloud backup where appropriate<\/li>\n<\/ul>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">18. MongoDB Administration Workflow<\/h2>\n\n\n\n<p>A MongoDB administrator is responsible for keeping the database secure, healthy, backed up, observable, and performant.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h3 class=\"wp-block-heading\">18.1 Daily Administration Checklist<\/h3>\n\n\n\n<p>Run these checks daily:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>db.adminCommand({ serverStatus: 1 })\n<\/code><\/pre>\n\n\n\n<p>Check database sizes:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>db.stats()\n<\/code><\/pre>\n\n\n\n<p>Check collection stats:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>db.books.stats()\n<\/code><\/pre>\n\n\n\n<p>Check current operations:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>db.currentOp()\n<\/code><\/pre>\n\n\n\n<p>Check replica set status:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>rs.status()\n<\/code><\/pre>\n\n\n\n<p>Check replication lag:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>rs.printSecondaryReplicationInfo()\n<\/code><\/pre>\n\n\n\n<p>Review logs:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>sudo journalctl -u mongod\n<\/code><\/pre>\n\n\n\n<p>or:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>sudo tail -f \/var\/log\/mongodb\/mongod.log\n<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h3 class=\"wp-block-heading\">18.2 Weekly Administration Checklist<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Review slow queries<\/li>\n\n\n\n<li>Review index usage<\/li>\n\n\n\n<li>Check disk growth<\/li>\n\n\n\n<li>Check backup restore process<\/li>\n\n\n\n<li>Review users and roles<\/li>\n\n\n\n<li>Check expired or unused accounts<\/li>\n\n\n\n<li>Confirm monitoring alerts<\/li>\n\n\n\n<li>Check OS patching plan<\/li>\n\n\n\n<li>Check MongoDB patch version<\/li>\n\n\n\n<li>Review schema growth and document sizes<\/li>\n<\/ul>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h3 class=\"wp-block-heading\">18.3 Monthly Administration Checklist<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Test disaster recovery<\/li>\n\n\n\n<li>Review capacity planning<\/li>\n\n\n\n<li>Audit access control<\/li>\n\n\n\n<li>Review TLS certificates<\/li>\n\n\n\n<li>Review shard balance if sharded<\/li>\n\n\n\n<li>Review replica set elections<\/li>\n\n\n\n<li>Confirm backup retention<\/li>\n\n\n\n<li>Check deprecated features before upgrades<\/li>\n<\/ul>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h3 class=\"wp-block-heading\">18.4 Common Admin Commands<\/h3>\n\n\n\n<p>Show databases:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>show dbs\n<\/code><\/pre>\n\n\n\n<p>Show users:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>show users\n<\/code><\/pre>\n\n\n\n<p>Show roles:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>show roles\n<\/code><\/pre>\n\n\n\n<p>Check server status:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>db.serverStatus()\n<\/code><\/pre>\n\n\n\n<p>Check build info:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>db.version()\ndb.adminCommand({ buildInfo: 1 })\n<\/code><\/pre>\n\n\n\n<p>Check database stats:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>db.stats()\n<\/code><\/pre>\n\n\n\n<p>Check collection stats:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>db.collection.stats()\n<\/code><\/pre>\n\n\n\n<p>Kill operation:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>db.killOp(opid)\n<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">19. MongoDB User Workflow<\/h2>\n\n\n\n<p>A MongoDB user workflow depends on role. Here are the main workflows.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h3 class=\"wp-block-heading\">19.1 Developer Workflow<\/h3>\n\n\n\n<ol class=\"wp-block-list\">\n<li>Understand application data.<\/li>\n\n\n\n<li>Design document model.<\/li>\n\n\n\n<li>Choose embedding or referencing.<\/li>\n\n\n\n<li>Create collections.<\/li>\n\n\n\n<li>Insert sample data.<\/li>\n\n\n\n<li>Write CRUD queries.<\/li>\n\n\n\n<li>Add indexes.<\/li>\n\n\n\n<li>Test with realistic data volume.<\/li>\n\n\n\n<li>Use <code>explain()<\/code> to inspect performance.<\/li>\n\n\n\n<li>Add schema validation where needed.<\/li>\n\n\n\n<li>Connect application using driver.<\/li>\n\n\n\n<li>Deploy with authentication and TLS.<\/li>\n\n\n\n<li>Monitor slow queries.<\/li>\n<\/ol>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h3 class=\"wp-block-heading\">19.2 Application Workflow<\/h3>\n\n\n\n<p>A typical application flow:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>User request\n  \u2193\nApplication route\/controller\n  \u2193\nValidate request\n  \u2193\nMongoDB driver query\n  \u2193\nMongoDB server\n  \u2193\nReturn document\/result\n  \u2193\nApplication response\n<\/code><\/pre>\n\n\n\n<p>Example: create a user.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>app.post(\"\/users\", async (req, res) =&gt; {\n  const result = await db.collection(\"users\").insertOne({\n    name: req.body.name,\n    email: req.body.email,\n    createdAt: new Date()\n  });\n\n  res.json({ id: result.insertedId });\n});\n<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h3 class=\"wp-block-heading\">19.3 Analyst Workflow<\/h3>\n\n\n\n<ol class=\"wp-block-list\">\n<li>Connect to read-only user.<\/li>\n\n\n\n<li>Explore collections.<\/li>\n\n\n\n<li>Use aggregation pipeline.<\/li>\n\n\n\n<li>Export selected results.<\/li>\n\n\n\n<li>Build reports.<\/li>\n\n\n\n<li>Avoid production-heavy queries without indexes.<\/li>\n\n\n\n<li>Coordinate large analytics jobs with admins.<\/li>\n<\/ol>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h3 class=\"wp-block-heading\">19.4 Admin Workflow<\/h3>\n\n\n\n<ol class=\"wp-block-list\">\n<li>Provision deployment.<\/li>\n\n\n\n<li>Configure storage and networking.<\/li>\n\n\n\n<li>Enable authentication.<\/li>\n\n\n\n<li>Create users and roles.<\/li>\n\n\n\n<li>Configure backups.<\/li>\n\n\n\n<li>Configure monitoring.<\/li>\n\n\n\n<li>Review indexes.<\/li>\n\n\n\n<li>Manage replica sets.<\/li>\n\n\n\n<li>Plan upgrades.<\/li>\n\n\n\n<li>Respond to incidents.<\/li>\n<\/ol>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">20. Performance Optimization<\/h2>\n\n\n\n<p>MongoDB performance depends on data model, indexes, working set, hardware, queries, and deployment architecture.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h3 class=\"wp-block-heading\">20.1 Use Proper Indexes<\/h3>\n\n\n\n<p>Bad:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>db.orders.find({ customerId: 12345 }).sort({ createdAt: -1 })\n<\/code><\/pre>\n\n\n\n<p>Without index, this may scan and sort many documents.<\/p>\n\n\n\n<p>Better:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>db.orders.createIndex({ customerId: 1, createdAt: -1 })\n<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h3 class=\"wp-block-heading\">20.2 Avoid Returning Too Much Data<\/h3>\n\n\n\n<p>Bad:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>db.users.find()\n<\/code><\/pre>\n\n\n\n<p>Better:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>db.users.find(\n  { status: \"active\" },\n  { name: 1, email: 1, _id: 0 }\n).limit(100)\n<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h3 class=\"wp-block-heading\">20.3 Avoid Unbounded Arrays<\/h3>\n\n\n\n<p>Bad design:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>{\n  userId: 1,\n  events: &#91;\n    thousands_or_millions_of_events\n  ]\n}\n<\/code><\/pre>\n\n\n\n<p>Better:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>{\n  userId: 1,\n  eventType: \"login\",\n  createdAt: ISODate(\"2026-01-01T10:00:00Z\")\n}\n<\/code><\/pre>\n\n\n\n<p>Store large event streams as separate documents.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h3 class=\"wp-block-heading\">20.4 Use <code>explain()<\/code><\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>db.orders.find({ customerId: 1001 }).explain(\"executionStats\")\n<\/code><\/pre>\n\n\n\n<p>Check:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Was an index used?<\/li>\n\n\n\n<li>How many documents were scanned?<\/li>\n\n\n\n<li>How long did it take?<\/li>\n\n\n\n<li>Is there a collection scan?<\/li>\n<\/ul>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h3 class=\"wp-block-heading\">20.5 Design for Query Patterns<\/h3>\n\n\n\n<p>Do not design MongoDB documents only by \u201cnormalization rules.\u201d Design for the way your application reads and writes data.<\/p>\n\n\n\n<p>Ask:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>What are the top 10 queries?<\/li>\n\n\n\n<li>What data is read together?<\/li>\n\n\n\n<li>What data changes frequently?<\/li>\n\n\n\n<li>What data grows forever?<\/li>\n\n\n\n<li>What fields need indexes?<\/li>\n\n\n\n<li>What fields need uniqueness?<\/li>\n\n\n\n<li>What operations must be atomic?<\/li>\n<\/ul>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">21. Advanced MongoDB Features<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\">21.1 TTL Indexes<\/h3>\n\n\n\n<p>TTL indexes automatically delete documents after a period of time.<\/p>\n\n\n\n<p>Example: delete logs after 30 days.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>db.logs.createIndex(\n  { createdAt: 1 },\n  { expireAfterSeconds: 2592000 }\n)\n<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h3 class=\"wp-block-heading\">21.2 Text Indexes<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>db.articles.createIndex({ title: \"text\", body: \"text\" })\n<\/code><\/pre>\n\n\n\n<p>Search:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>db.articles.find({ $text: { $search: \"mongodb tutorial\" } })\n<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h3 class=\"wp-block-heading\">21.3 Geospatial Indexes<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>db.places.createIndex({ location: \"2dsphere\" })\n<\/code><\/pre>\n\n\n\n<p>Example document:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>{\n  name: \"Tokyo Station\",\n  location: {\n    type: \"Point\",\n    coordinates: &#91;139.7671, 35.6812]\n  }\n}\n<\/code><\/pre>\n\n\n\n<p>Find nearby:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>db.places.find({\n  location: {\n    $near: {\n      $geometry: {\n        type: \"Point\",\n        coordinates: &#91;139.7671, 35.6812]\n      },\n      $maxDistance: 1000\n    }\n  }\n})\n<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h3 class=\"wp-block-heading\">21.4 Change Streams<\/h3>\n\n\n\n<p>Change streams allow applications to listen for database changes.<\/p>\n\n\n\n<p>Example:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>const changeStream = db.collection(\"orders\").watch();\n\nchangeStream.on(\"change\", change =&gt; {\n  console.log(change);\n});\n<\/code><\/pre>\n\n\n\n<p>Use cases:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Real-time notifications<\/li>\n\n\n\n<li>Cache invalidation<\/li>\n\n\n\n<li>Event-driven systems<\/li>\n\n\n\n<li>Audit pipelines<\/li>\n<\/ul>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h3 class=\"wp-block-heading\">21.5 Capped Collections<\/h3>\n\n\n\n<p>Capped collections have fixed size and preserve insertion order.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>db.createCollection(\"logs\", {\n  capped: true,\n  size: 100000\n})\n<\/code><\/pre>\n\n\n\n<p>Use for:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Logs<\/li>\n\n\n\n<li>Event buffers<\/li>\n\n\n\n<li>Temporary streams<\/li>\n<\/ul>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">22. Complete Mini Project: Bookstore Database<\/h2>\n\n\n\n<p>Now let\u2019s build a small bookstore database.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h3 class=\"wp-block-heading\">22.1 Create Database<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>use bookstore\n<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h3 class=\"wp-block-heading\">22.2 Create Collections<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>db.createCollection(\"users\")\ndb.createCollection(\"books\")\ndb.createCollection(\"orders\")\n<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h3 class=\"wp-block-heading\">22.3 Insert Users<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>db.users.insertMany(&#91;\n  {\n    name: \"Alice\",\n    email: \"alice@example.com\",\n    role: \"customer\",\n    createdAt: new Date()\n  },\n  {\n    name: \"Bob\",\n    email: \"bob@example.com\",\n    role: \"customer\",\n    createdAt: new Date()\n  }\n])\n<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h3 class=\"wp-block-heading\">22.4 Insert Books<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>db.books.insertMany(&#91;\n  {\n    title: \"MongoDB Basics\",\n    author: \"Alice Tanaka\",\n    category: \"Database\",\n    price: 29.99,\n    stock: 50,\n    tags: &#91;\"mongodb\", \"nosql\"]\n  },\n  {\n    title: \"Docker Practical Guide\",\n    author: \"Maria Silva\",\n    category: \"DevOps\",\n    price: 39.99,\n    stock: 20,\n    tags: &#91;\"docker\", \"containers\"]\n  },\n  {\n    title: \"Linux for Beginners\",\n    author: \"Ken Sato\",\n    category: \"Linux\",\n    price: 24.99,\n    stock: 100,\n    tags: &#91;\"linux\", \"server\"]\n  }\n])\n<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h3 class=\"wp-block-heading\">22.5 Create Indexes<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>db.users.createIndex({ email: 1 }, { unique: true })\ndb.books.createIndex({ title: 1 })\ndb.books.createIndex({ category: 1, price: -1 })\ndb.orders.createIndex({ userId: 1, createdAt: -1 })\n<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h3 class=\"wp-block-heading\">22.6 Create an Order<\/h3>\n\n\n\n<p>Find user:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>const user = db.users.findOne({ email: \"alice@example.com\" })\n<\/code><\/pre>\n\n\n\n<p>Find books:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>const book1 = db.books.findOne({ title: \"MongoDB Basics\" })\nconst book2 = db.books.findOne({ title: \"Docker Practical Guide\" })\n<\/code><\/pre>\n\n\n\n<p>Insert order:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>db.orders.insertOne({\n  userId: user._id,\n  customerEmail: user.email,\n  items: &#91;\n    {\n      bookId: book1._id,\n      title: book1.title,\n      qty: 1,\n      price: book1.price\n    },\n    {\n      bookId: book2._id,\n      title: book2.title,\n      qty: 1,\n      price: book2.price\n    }\n  ],\n  total: book1.price + book2.price,\n  status: \"paid\",\n  createdAt: new Date()\n})\n<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h3 class=\"wp-block-heading\">22.7 Reduce Stock<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>db.books.updateOne(\n  { _id: book1._id },\n  { $inc: { stock: -1 } }\n)\n\ndb.books.updateOne(\n  { _id: book2._id },\n  { $inc: { stock: -1 } }\n)\n<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h3 class=\"wp-block-heading\">22.8 Sales Report<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>db.orders.aggregate(&#91;\n  { $match: { status: \"paid\" } },\n  { $unwind: \"$items\" },\n  {\n    $group: {\n      _id: \"$items.title\",\n      totalSold: { $sum: \"$items.qty\" },\n      revenue: {\n        $sum: { $multiply: &#91;\"$items.qty\", \"$items.price\"] }\n      }\n    }\n  },\n  { $sort: { revenue: -1 } }\n])\n<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">23. MongoDB Best Practices<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\">23.1 Data Modeling Best Practices<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Model data around application queries.<\/li>\n\n\n\n<li>Embed data that is read together.<\/li>\n\n\n\n<li>Reference data that is large, shared, or independent.<\/li>\n\n\n\n<li>Avoid unbounded arrays.<\/li>\n\n\n\n<li>Keep document size reasonable.<\/li>\n\n\n\n<li>Use schema validation for critical collections.<\/li>\n\n\n\n<li>Store duplicate read-optimized fields when useful, but keep them consistent.<\/li>\n<\/ul>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h3 class=\"wp-block-heading\">23.2 Query Best Practices<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Use indexes for frequent queries.<\/li>\n\n\n\n<li>Use projection to return only needed fields.<\/li>\n\n\n\n<li>Use pagination for large result sets.<\/li>\n\n\n\n<li>Avoid regex queries without proper index strategy.<\/li>\n\n\n\n<li>Avoid collection scans on large collections.<\/li>\n\n\n\n<li>Use aggregation carefully on large datasets.<\/li>\n<\/ul>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h3 class=\"wp-block-heading\">23.3 Index Best Practices<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Create indexes based on real queries.<\/li>\n\n\n\n<li>Use compound indexes for filter + sort patterns.<\/li>\n\n\n\n<li>Avoid too many indexes.<\/li>\n\n\n\n<li>Remove unused indexes.<\/li>\n\n\n\n<li>Use unique indexes for unique fields.<\/li>\n\n\n\n<li>Test indexes with <code>explain()<\/code>.<\/li>\n<\/ul>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h3 class=\"wp-block-heading\">23.4 Security Best Practices<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Enable authentication.<\/li>\n\n\n\n<li>Use least-privilege roles.<\/li>\n\n\n\n<li>Do not use admin users in applications.<\/li>\n\n\n\n<li>Use TLS in production.<\/li>\n\n\n\n<li>Rotate passwords and secrets.<\/li>\n\n\n\n<li>Keep MongoDB patched.<\/li>\n\n\n\n<li>Restrict network access.<\/li>\n\n\n\n<li>Audit users and roles regularly.<\/li>\n<\/ul>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h3 class=\"wp-block-heading\">23.5 Backup Best Practices<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Automate backups.<\/li>\n\n\n\n<li>Test restores.<\/li>\n\n\n\n<li>Store backups securely.<\/li>\n\n\n\n<li>Use snapshots or managed backups for production.<\/li>\n\n\n\n<li>Monitor backup jobs.<\/li>\n\n\n\n<li>Document recovery procedures.<\/li>\n<\/ul>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h3 class=\"wp-block-heading\">23.6 Production Best Practices<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Use replica sets.<\/li>\n\n\n\n<li>Monitor disk, CPU, memory, connections, locks, and replication lag.<\/li>\n\n\n\n<li>Use proper indexes.<\/li>\n\n\n\n<li>Plan capacity.<\/li>\n\n\n\n<li>Avoid running without authentication.<\/li>\n\n\n\n<li>Avoid public internet exposure.<\/li>\n\n\n\n<li>Use sharding only when required.<\/li>\n\n\n\n<li>Test upgrades before production.<\/li>\n\n\n\n<li>Keep disaster recovery plans current.<\/li>\n<\/ul>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">24. Common Mistakes Beginners Make<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\">Mistake 1: Thinking MongoDB Has No Schema<\/h3>\n\n\n\n<p>MongoDB has a flexible schema, but your application still needs a clear data model.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Mistake 2: Creating Too Many Indexes<\/h3>\n\n\n\n<p>Indexes speed up reads but slow down writes and use storage.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Mistake 3: Using MongoDB Like a Relational Database<\/h3>\n\n\n\n<p>If every query requires many joins, your model may not be document-oriented enough.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Mistake 4: Ignoring Backups<\/h3>\n\n\n\n<p>Backups are only useful if restores are tested.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Mistake 5: Running Without Authentication<\/h3>\n\n\n\n<p>Self-managed MongoDB access control is not enabled by default, so you must enable it for real deployments. (<a href=\"https:\/\/www.mongodb.com\/docs\/manual\/core\/authorization\/\">MongoDB<\/a>)<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Mistake 6: Bad Shard Key<\/h3>\n\n\n\n<p>A poor shard key can create uneven data distribution and performance hot spots.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Mistake 7: Not Using <code>explain()<\/code><\/h3>\n\n\n\n<p>You cannot guess query performance reliably. Use <code>explain()<\/code>.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">25. MongoDB Cheat Sheet<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\">Database Commands<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>show dbs\nuse mydb\ndb\ndb.dropDatabase()\n<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Collection Commands<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>show collections\ndb.createCollection(\"users\")\ndb.users.drop()\n<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Insert<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>db.users.insertOne({ name: \"Alice\" })\ndb.users.insertMany(&#91;{ name: \"Bob\" }, { name: \"Carol\" }])\n<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Read<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>db.users.find()\ndb.users.findOne({ name: \"Alice\" })\ndb.users.find({ age: { $gt: 18 } })\n<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Projection<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>db.users.find({}, { name: 1, email: 1, _id: 0 })\n<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Update<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>db.users.updateOne(\n  { name: \"Alice\" },\n  { $set: { city: \"Tokyo\" } }\n)\n\ndb.users.updateMany(\n  { active: true },\n  { $set: { verified: true } }\n)\n<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Delete<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>db.users.deleteOne({ name: \"Alice\" })\ndb.users.deleteMany({ active: false })\n<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Index<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>db.users.createIndex({ email: 1 }, { unique: true })\ndb.users.getIndexes()\ndb.users.dropIndex({ email: 1 })\n<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Aggregation<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>db.orders.aggregate(&#91;\n  { $match: { status: \"paid\" } },\n  { $group: { _id: \"$customer\", total: { $sum: \"$total\" } } },\n  { $sort: { total: -1 } }\n])\n<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Users<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>use admin\n\ndb.createUser({\n  user: \"adminUser\",\n  pwd: passwordPrompt(),\n  roles: &#91;\"root\"]\n})\n<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Backup<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>mongodump --db mydb --out \/backup\n<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Restore<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>mongorestore --db mydb \/backup\/mydb\n<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">26. Suggested Learning Path<\/h2>\n\n\n\n<p>Follow this order:<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li>Understand documents, collections, and databases.<\/li>\n\n\n\n<li>Install MongoDB locally with Docker.<\/li>\n\n\n\n<li>Learn <code>mongosh<\/code>.<\/li>\n\n\n\n<li>Practice CRUD.<\/li>\n\n\n\n<li>Learn filters, projections, sorting, and pagination.<\/li>\n\n\n\n<li>Learn data modeling.<\/li>\n\n\n\n<li>Learn indexes.<\/li>\n\n\n\n<li>Learn aggregation.<\/li>\n\n\n\n<li>Add schema validation.<\/li>\n\n\n\n<li>Add authentication and users.<\/li>\n\n\n\n<li>Learn backup and restore.<\/li>\n\n\n\n<li>Learn replica sets.<\/li>\n\n\n\n<li>Learn transactions.<\/li>\n\n\n\n<li>Learn sharding concepts.<\/li>\n\n\n\n<li>Learn monitoring and production administration.<\/li>\n<\/ol>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">Final Summary<\/h2>\n\n\n\n<p>MongoDB is a flexible, document-oriented database designed for modern applications. Its biggest strengths are flexible schema design, document-based storage, powerful queries, indexes, aggregation, replication, transactions, and horizontal scaling through sharding.<\/p>\n\n\n\n<p>For beginners, start with Docker, <code>mongosh<\/code>, CRUD, and indexes. For intermediate users, focus on schema design, aggregation, validation, and security. For advanced users, learn replica sets, backup strategies, performance tuning, transactions, and sharding.<\/p>\n\n\n\n<p>A strong MongoDB workflow is:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>Design data model\n  \u2193\nCreate collections\n  \u2193\nInsert documents\n  \u2193\nQuery and update data\n  \u2193\nAdd indexes\n  \u2193\nValidate schema\n  \u2193\nSecure users and roles\n  \u2193\nBack up data\n  \u2193\nMonitor performance\n  \u2193\nScale with replica sets and sharding\n<\/code><\/pre>\n\n\n\n<p>That is the practical end-to-end MongoDB journey: from first document to production-ready database.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>MongoDB is a NoSQL document database. Instead of storing data in rows and columns like a relational database, MongoDB stores data as documents inside collections. These documents&#8230; <\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[1],"tags":[],"class_list":["post-990","post","type-post","status-publish","format-standard","hentry","category-uncategorized"],"_links":{"self":[{"href":"https:\/\/www.devopsschool.com\/tutorials\/wp-json\/wp\/v2\/posts\/990","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.devopsschool.com\/tutorials\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.devopsschool.com\/tutorials\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.devopsschool.com\/tutorials\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.devopsschool.com\/tutorials\/wp-json\/wp\/v2\/comments?post=990"}],"version-history":[{"count":1,"href":"https:\/\/www.devopsschool.com\/tutorials\/wp-json\/wp\/v2\/posts\/990\/revisions"}],"predecessor-version":[{"id":991,"href":"https:\/\/www.devopsschool.com\/tutorials\/wp-json\/wp\/v2\/posts\/990\/revisions\/991"}],"wp:attachment":[{"href":"https:\/\/www.devopsschool.com\/tutorials\/wp-json\/wp\/v2\/media?parent=990"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.devopsschool.com\/tutorials\/wp-json\/wp\/v2\/categories?post=990"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.devopsschool.com\/tutorials\/wp-json\/wp\/v2\/tags?post=990"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}