├── 01 Installation.md ├── 02 Advantages.md ├── 03 Data types and structure.md ├── 04 Document-oriented data.md ├── 05 MongoDB Getting Started.md ├── 06 MongoDB Query API.md ├── 07 MongoDB mongosh Create Database.md ├── 08 MongoDB mongosh Create Collection.md ├── 09 MongoDB mongosh Insert.md ├── 10 MongoDB mongosh Find.md ├── 11 MongoDB mongosh Update.md ├── 12 MongoDB mongosh Delete.md ├── 13 MongoDB Query Operators.md ├── 14 MongoDB Update Operators.md ├── 15 MongoDB Aggregation Pipelines.md ├── 16 Indexing & Search.md ├── Example 01.py ├── Example 02.py ├── Example 03.py ├── Example 04.py ├── Example_allinone.js ├── LICENSE └── README.md /01 Installation.md: -------------------------------------------------------------------------------- 1 | # Installation and setup Mongo DB 2 | 3 | Installing and setting up MongoDB is a straightforward process. MongoDB provides official installation packages and guides for various operating systems, including Windows, macOS, and Linux. In this guide, I'll provide general instructions for getting MongoDB up and running. However, please check the official MongoDB website for the most up-to-date instructions and version-specific details. 4 | 5 | ## Installing MongoDB 6 | 7 | ### For Windows: 8 | 9 | 1. Visit the MongoDB download center at [MongoDB Download Center](https://www.mongodb.com/try/download/community) and select the Windows version. 10 | 11 | 2. Download the installer that matches your Windows version (64-bit or 32-bit). 12 | 13 | 3. Run the installer and follow the installation wizard. You can choose the installation directory and other options during the installation. 14 | 15 | 4. MongoDB Compass, a graphical user interface for MongoDB, is also available as part of the installation. You can choose to install it if you wish. 16 | 17 | ### For macOS: 18 | 19 | 1. Visit the MongoDB download center at [MongoDB Download Center](https://www.mongodb.com/try/download/community) and select the macOS version. 20 | 21 | 2. Download the macOS .tgz file. 22 | 23 | 3. Open a terminal and navigate to the directory where the downloaded file is located. 24 | 25 | 4. Extract the archive by running the following command, replacing `` with the MongoDB version number: 26 | 27 | ```bash 28 | tar -zxvf mongodb-macos-x86_64-.tgz 29 | ``` 30 | 31 | 5. Move the extracted MongoDB directory to a location of your choice. You can use the `mv` command: 32 | 33 | ```bash 34 | mv mongodb-macos-x86_64- /usr/local/mongodb 35 | ``` 36 | 37 | 6. You may want to add the MongoDB binaries to your system's PATH to make it easier to run MongoDB commands from the terminal. Add the following line to your shell profile file (e.g., `~/.bashrc`, `~/.zshrc`): 38 | 39 | ```bash 40 | export PATH="/usr/local/mongodb/bin:$PATH" 41 | ``` 42 | 43 | 7. Save the file and then run the following command to update your shell with the new PATH: 44 | 45 | ```bash 46 | source ~/.bashrc 47 | ``` 48 | 49 | ### For Linux (Ubuntu as an example): 50 | 51 | 1. Visit the MongoDB download center at [MongoDB Download Center](https://www.mongodb.com/try/download/community) and select the Linux version. 52 | 53 | 2. Download the .tgz file for your Linux distribution. 54 | 55 | 3. Open a terminal and navigate to the directory where the downloaded file is located. 56 | 57 | 4. Extract the archive by running the following command, replacing `` with the MongoDB version number: 58 | 59 | ```bash 60 | tar -zxvf mongodb-linux-x86_64-.tgz 61 | ``` 62 | 63 | 5. Move the extracted MongoDB directory to a location of your choice: 64 | 65 | ```bash 66 | sudo mv mongodb-linux-x86_64- /usr/local/mongodb 67 | ``` 68 | 69 | 6. You can add MongoDB to your PATH by adding the following line to your `.bashrc` or `.zshrc` file: 70 | 71 | ```bash 72 | export PATH="/usr/local/mongodb/bin:$PATH" 73 | ``` 74 | 75 | 7. Save the file and then run the following command to update your shell with the new PATH: 76 | 77 | ```bash 78 | source ~/.bashrc 79 | ``` 80 | 81 | ## Starting MongoDB 82 | 83 | Once MongoDB is installed, you can start the MongoDB server using the following steps: 84 | 85 | ### For Windows: 86 | 87 | 1. Open a Command Prompt as an administrator. 88 | 89 | 2. Navigate to the MongoDB installation directory (e.g., `C:\Program Files\MongoDB\Server\\bin`). 90 | 91 | 3. Run the following command to start the MongoDB server: 92 | 93 | ```bash 94 | mongod 95 | ``` 96 | 97 | ### For macOS and Linux: 98 | 99 | 1. Open a terminal. 100 | 101 | 2. Run the following command to start the MongoDB server: 102 | 103 | ```bash 104 | mongod 105 | ``` 106 | 107 | By default, MongoDB will run on the standard port 27017. 108 | 109 | ## Connecting to MongoDB 110 | 111 | To connect to the MongoDB server, open a new terminal or Command Prompt window and use the `mongo` shell: 112 | 113 | ```bash 114 | mongo 115 | ``` 116 | 117 | This will connect to the local MongoDB server by default. 118 | 119 | Now you have MongoDB installed and running, ready for you to create databases, collections, and start working with your data. 120 | -------------------------------------------------------------------------------- /02 Advantages.md: -------------------------------------------------------------------------------- 1 | MongoDB is a popular NoSQL database that offers a range of advantages for developers and businesses. Here are some of the key advantages of using MongoDB: 2 | 3 | 1. **Schema Flexibility**: 4 | - MongoDB is a document-oriented database, which means it stores data in flexible, semi-structured BSON (Binary JSON) format. This allows for easy and dynamic schema design, making it ideal for applications with evolving data requirements. You can store documents with different structures in the same collection. 5 | 6 | 2. **Horizontal Scalability**: 7 | - MongoDB is designed for horizontal scalability. You can distribute your data across multiple servers or clusters to handle large datasets and high traffic loads. This makes it a great choice for applications that need to scale seamlessly. 8 | 9 | 3. **High Performance**: 10 | - MongoDB is optimized for high write loads and read-heavy workloads. It can handle a large volume of data and concurrent requests efficiently. Features like automatic sharding and load balancing help maintain performance as data grows. 11 | 12 | 4. **Rich Query Language**: 13 | - MongoDB provides a powerful query language that supports various query operators, geospatial queries, and text search. You can easily express complex queries to retrieve and manipulate data. 14 | 15 | 5. **Aggregation Framework**: 16 | - MongoDB's aggregation framework allows you to process and analyze data within the database, making it suitable for performing operations like grouping, filtering, and calculating aggregates. 17 | 18 | 6. **Indexing**: 19 | - MongoDB supports various indexing options to improve query performance. You can create indexes on specific fields to accelerate query execution. 20 | 21 | 7. **Replication and Fault Tolerance**: 22 | - MongoDB offers built-in replication, allowing you to create replica sets for data redundancy and high availability. If one server goes down, the database can automatically failover to a secondary node, ensuring data integrity. 23 | 24 | 8. **Flexible Document Storage**: 25 | - MongoDB can store complex data structures, including arrays and nested documents, making it well-suited for applications where data relationships are complex. 26 | 27 | 9. **Ease of Use**: 28 | - MongoDB's intuitive document-based data model and flexible schema design make it easier to work with, especially for developers. It minimizes the need for complex migrations when evolving the data structure. 29 | 30 | 10. **Community and Support**: 31 | - MongoDB has a large and active community, providing access to tutorials, forums, and resources for developers. Additionally, MongoDB, Inc. offers commercial support and a suite of tools for managing and monitoring MongoDB deployments. 32 | 33 | 11. **Geospatial Capabilities**: 34 | - MongoDB has built-in support for geospatial data and queries, making it suitable for location-based services and applications that require geographic data. 35 | 36 | 12. **Open Source and Enterprise Edition**: 37 | - MongoDB is available in both open-source and enterprise editions. The open-source version is free to use, while the enterprise edition offers advanced features, support, and security options for business-critical applications. 38 | 39 | 13. **Security Features**: 40 | - MongoDB offers robust security features, including authentication, authorization, role-based access control, and encryption. This helps protect data from unauthorized access. 41 | 42 | 14. **Document Versioning and Change Streams**: 43 | - MongoDB provides features like document versioning and change streams, which are valuable for tracking changes and maintaining historical data records. 44 | 45 | 15. **Cloud Integration**: 46 | - MongoDB offers cloud-native versions, such as MongoDB Atlas, which simplifies database management, automatic scaling, and backups in cloud environments like AWS, Azure, and Google Cloud. 47 | 48 | 16. **Big Data and Analytics Integration**: 49 | - MongoDB can be integrated with big data and analytics platforms, making it a versatile choice for applications that require real-time data analysis. 50 | 51 | These advantages make MongoDB a compelling choice for a wide range of applications, from web and mobile applications to data analytics, content management systems, and more. However, it's essential to evaluate your specific project requirements to determine if MongoDB is the right fit for your use case. 52 | -------------------------------------------------------------------------------- /03 Data types and structure.md: -------------------------------------------------------------------------------- 1 | In MongoDB, data is stored in BSON (Binary JSON) format, providing flexibility in document structure. Here are key MongoDB data types and concepts: 2 | 3 | 1. **Basic Data Types:** 4 | - **String:** Represents textual data. 5 | - **Number (Integer/Double):** Supports both 32-bit and 64-bit integers, as well as double-precision floating-point numbers. 6 | - **Boolean:** Represents `true` or `false` values. 7 | - **Date:** Stores date and time information. 8 | - **ObjectId:** A 12-byte identifier unique within a collection. 9 | 10 | 2. **Arrays:** 11 | - **Array:** An ordered list of values, where each element can be of any data type, including other arrays. 12 | 13 | 3. **Embedded Documents:** 14 | - **Document:** MongoDB documents can contain nested documents, allowing for hierarchical structures. 15 | 16 | 4. **Null and Undefined:** 17 | - **Null:** Represents a null or nonexistent value. 18 | - **Undefined:** Represents a field that does not exist or has an undefined value. 19 | 20 | 5. **Geospatial Data Types:** 21 | - Supports geospatial data types like `Point`, `LineString`, and `Polygon` for location-based queries. 22 | 23 | 6. **Binary Data:** 24 | - **Binary Data:** Stores binary information, suitable for file storage or large data sets. 25 | 26 | 7. **Regular Expressions:** 27 | - **Regular Expression:** Enables pattern matching within queries. 28 | 29 | 8. **Min/Max Keys:** 30 | - **MinKey and MaxKey:** Special values representing the smallest and largest BSON elements, respectively. 31 | 32 | 9. **Timestamp:** 33 | - **Timestamp:** Represents a 64-bit value containing the seconds since the Unix epoch. 34 | 35 | 10. **Symbol:** 36 | - **Symbol:** Stores a symbol, primarily used in languages like JavaScript. 37 | 38 | ### Example Document: 39 | ```javascript 40 | { 41 | "_id": ObjectId("5f0a08f8e260187f16b95154"), 42 | "name": "John Doe", 43 | "age": 30, 44 | "isStudent": false, 45 | "address": { 46 | "city": "New York", 47 | "zipcode": "10001" 48 | }, 49 | "hobbies": ["reading", "gaming"], 50 | "createdAt": ISODate("2022-01-01T12:00:00Z"), 51 | "profilePicture": BinData(0, "base64_encoded_data") 52 | } 53 | ``` 54 | 55 | This example illustrates a document with various data types, embedded documents, arrays, and an ObjectId. MongoDB's flexibility allows for diverse data structures, adapting to the needs of your application. -------------------------------------------------------------------------------- /04 Document-oriented data.md: -------------------------------------------------------------------------------- 1 | #MongoDB document-oriented database: 2 | 3 | ### Step 1: Install MongoDB 4 | - Install MongoDB on your system. You can follow the official MongoDB installation guide for your specific operating system. 5 | 6 | ### Step 2: Start MongoDB 7 | - Start the MongoDB server. For most installations, you can do this by running the `mongod` command in your terminal or command prompt. 8 | 9 | ### Step 3: Connect to MongoDB 10 | - Open a new terminal or command prompt and run the `mongo` command to connect to the MongoDB server. 11 | 12 | ### Step 4: Create a Database 13 | - Use the `use` command to create a new database. For example: 14 | ```bash 15 | use mydatabase 16 | ``` 17 | 18 | ### Step 5: Create a Collection 19 | - Collections are analogous to tables in relational databases. Create a collection using the `db.createCollection` command: 20 | ```bash 21 | db.createCollection("mycollection") 22 | ``` 23 | 24 | ### Step 6: Insert Documents 25 | - MongoDB stores data in BSON format (Binary JSON). Insert documents into your collection using the `insertOne` or `insertMany` command. For example: 26 | ```bash 27 | db.mycollection.insertOne({ 28 | name: "John Doe", 29 | age: 30, 30 | city: "New York" 31 | }) 32 | ``` 33 | 34 | ### Step 7: Query Documents 35 | - Retrieve data using the `find` command. For example: 36 | ```bash 37 | db.mycollection.find() 38 | ``` 39 | 40 | ### Step 8: Update Documents 41 | - Update documents using the `updateOne` or `updateMany` command. For example: 42 | ```bash 43 | db.mycollection.updateOne( 44 | { name: "John Doe" }, 45 | { $set: { age: 31 } } 46 | ) 47 | ``` 48 | 49 | ### Step 9: Delete Documents 50 | - Remove documents using the `deleteOne` or `deleteMany` command. For example: 51 | ```bash 52 | db.mycollection.deleteOne({ name: "John Doe" }) 53 | ``` 54 | 55 | ### Step 10: Indexing (Optional) 56 | - Indexes can improve query performance. You can create an index using the `createIndex` command. For example: 57 | ```bash 58 | db.mycollection.createIndex({ name: 1 }) 59 | ``` 60 | 61 | This is a basic overview. MongoDB offers many more features and capabilities, so it's worth exploring the official documentation for more in-depth information. -------------------------------------------------------------------------------- /05 MongoDB Getting Started.md: -------------------------------------------------------------------------------- 1 | # MongoDB Getting Started 2 | 3 | To get started with MongoDB, you'll need to install it on your machine. Here are the general steps for installing MongoDB: 4 | 5 | ### Step 1: Download MongoDB 6 | 7 | 1. Go to the official MongoDB website: [MongoDB Download Center](https://www.mongodb.com/try/download/community). 8 | 9 | 2. Choose the appropriate version of MongoDB for your operating system. For example, if you're using Windows, select the Windows tab. If you're using macOS, select the macOS tab. 10 | 11 | 3. Download the installer package for your operating system. 12 | 13 | ### Step 2: Install MongoDB 14 | 15 | #### Windows: 16 | 17 | 1. Run the downloaded installer (.msi) file. 18 | 19 | 2. Follow the installation wizard, and choose the "Complete" setup type for a standard installation. 20 | 21 | 3. MongoDB will be installed in the "C:\Program Files\MongoDB\Server\" directory by default. 22 | 23 | #### macOS: 24 | 25 | 1. Open the downloaded .dmg file. 26 | 27 | 2. Drag the MongoDB icon to the Applications folder. 28 | 29 | #### Linux: 30 | 31 | 1. Extract the downloaded tar.gz file to a location of your choice. 32 | 33 | ```bash 34 | tar -zxvf mongodb-linux-*-.tgz 35 | ``` 36 | 37 | 2. Move the extracted folder to a desired location, for example: 38 | 39 | ```bash 40 | sudo mv mongodb-linux-*- /usr/local/mongodb 41 | ``` 42 | 43 | ### Step 3: Set Up MongoDB Environment 44 | 45 | #### Windows: 46 | 47 | 1. Add the MongoDB bin directory to the system PATH: 48 | - Open the System Properties. 49 | - Click on "Environment Variables." 50 | - In the "System Variables" section, select the "Path" variable, then click "Edit." 51 | - Add a new entry for the MongoDB bin directory (e.g., C:\Program Files\MongoDB\Server\\bin). 52 | 53 | 2. Create a data directory for MongoDB. The default data directory is `C:\data\db`. Create this directory or specify a different one by setting the `dbpath` in the MongoDB configuration. 54 | 55 | #### macOS/Linux: 56 | 57 | 1. Add the MongoDB bin directory to the system PATH by adding the following line to your shell configuration file (e.g., `~/.bashrc`, `~/.bash_profile`, `~/.zshrc`): 58 | 59 | ```bash 60 | export PATH=/usr/local/mongodb/bin:$PATH 61 | ``` 62 | 63 | 2. Create a data directory for MongoDB. The default data directory is `/data/db`. Create this directory or specify a different one by setting the `dbpath` in the MongoDB configuration. 64 | 65 | ### Step 4: Start MongoDB 66 | 67 | 1. Open a terminal or command prompt. 68 | 69 | 2. Run the MongoDB server: 70 | 71 | ```bash 72 | mongod 73 | ``` 74 | 75 | This command starts the MongoDB server. Leave the terminal or command prompt open while the server is running. 76 | 77 | ### Step 5: Connect to MongoDB 78 | 79 | 1. Open a new terminal or command prompt. 80 | 81 | 2. Run the MongoDB shell: 82 | 83 | ```bash 84 | mongo 85 | ``` 86 | 87 | Now you can start interacting with MongoDB using the MongoDB shell. 88 | 89 | Congratulations! You've successfully installed MongoDB on your machine and are ready to start working with it. Remember to consult the MongoDB documentation for more in-depth information and usage guides: [MongoDB Documentation](https://docs.mongodb.com/). 90 | -------------------------------------------------------------------------------- /06 MongoDB Query API.md: -------------------------------------------------------------------------------- 1 | ### Step-by-Step Tutorial: Creating a MongoDB Database Using `mongosh` 2 | 3 | #### Step 1: Install MongoDB 4 | 5 | Before you can use `mongosh` (MongoDB Shell), ensure you have MongoDB installed on your machine. You can download and install it from the [MongoDB official website](https://www.mongodb.com/try/download/community). 6 | 7 | #### Step 2: Install MongoDB Shell (`mongosh`) 8 | 9 | MongoDB Shell (`mongosh`) is the new shell that comes with MongoDB. You can download and install `mongosh` from the [MongoDB Shell download page](https://www.mongodb.com/try/download/shell). 10 | 11 | #### Step 3: Start MongoDB 12 | 13 | Make sure your MongoDB server is running. You can start it by executing the following command in your terminal: 14 | 15 | ```sh 16 | mongod 17 | ``` 18 | 19 | #### Step 4: Open MongoDB Shell (`mongosh`) 20 | 21 | Once your MongoDB server is running, open a new terminal window and start the MongoDB Shell by typing: 22 | 23 | ```sh 24 | mongosh 25 | ``` 26 | 27 | This will open the MongoDB Shell, and you'll see a prompt like this: 28 | 29 | ```sh 30 | Current Mongosh Log ID: 60b6e0a... 31 | Connecting to: mongodb://localhost:27017 32 | MongoDB server version: 4.4.6 33 | ``` 34 | 35 | #### Step 5: Create a New Database 36 | 37 | In MongoDB, databases are created dynamically. You don't need to explicitly create a database. Instead, you can simply switch to a new database, and it will be created when you insert data into it. To switch to a new database, use the `use` command followed by the database name. For example, to create a database named `codeswithpankaj`, you would type: 38 | 39 | ```sh 40 | use codeswithpankaj 41 | ``` 42 | 43 | You should see a confirmation message like this: 44 | 45 | ```sh 46 | switched to db codeswithpankaj 47 | ``` 48 | 49 | #### Step 6: Create a Collection 50 | 51 | In MongoDB, data is stored in collections. A collection is similar to a table in relational databases. To create a collection, you can use the `db.createCollection` method. For example, to create a collection named `users`, type: 52 | 53 | ```sh 54 | db.createCollection("users") 55 | ``` 56 | 57 | You should see a confirmation message like this: 58 | 59 | ```sh 60 | { ok: 1 } 61 | ``` 62 | 63 | #### Step 7: Insert Documents into the Collection 64 | 65 | Now that you have a collection, you can insert documents (records) into it. To insert a document, use the `insertOne` method. For example, to insert a user document, type: 66 | 67 | ```sh 68 | db.users.insertOne({ name: "Pankaj", age: 30, email: "pankaj@example.com" }) 69 | ``` 70 | 71 | You should see a confirmation message like this: 72 | 73 | ```sh 74 | { 75 | acknowledged: true, 76 | insertedId: ObjectId("60b6e0a...") 77 | } 78 | ``` 79 | 80 | #### Step 8: Query the Collection 81 | 82 | To verify that your document was inserted, you can query the collection using the `find` method. For example, to find all documents in the `users` collection, type: 83 | 84 | ```sh 85 | db.users.find() 86 | ``` 87 | 88 | You should see the inserted document(s): 89 | 90 | ```sh 91 | [ 92 | { _id: ObjectId("60b6e0a..."), name: "Pankaj", age: 30, email: "pankaj@example.com" } 93 | ] 94 | ``` 95 | 96 | #### Step 9: Verify the Database Creation 97 | 98 | To verify that your database has been created, you can list all databases using the `show dbs` command. However, note that the database will not appear in the list until it contains data. Since we have already inserted a document, you should see `codeswithpankaj` in the list: 99 | 100 | ```sh 101 | show dbs 102 | ``` 103 | 104 | You should see something like this: 105 | 106 | ```sh 107 | admin 0.000GB 108 | codeswithpankaj 0.001GB 109 | config 0.000GB 110 | local 0.000GB 111 | ``` 112 | 113 | #### Summary 114 | 115 | Congratulations! You have successfully created a MongoDB database named `codeswithpankaj` and added a collection with some data using `mongosh`. 116 | 117 | In summary, the steps are: 118 | 1. Install MongoDB and `mongosh`. 119 | 2. Start the MongoDB server. 120 | 3. Open `mongosh`. 121 | 4. Use the `use` command to create and switch to a new database. 122 | 5. Create a collection using `db.createCollection`. 123 | 6. Insert documents using `insertOne`. 124 | 7. Query the collection using `find`. 125 | 8. Verify the database creation using `show dbs`. 126 | 127 | -------------------------------------------------------------------------------- /07 MongoDB mongosh Create Database.md: -------------------------------------------------------------------------------- 1 | # Create a MongoDB database 2 | # Check the list of databases 3 | 4 | --- 5 | 6 | ### **Steps to Create a Database in MongoDB** 7 | 1. Use the `use ` command to switch to or create a new database. 8 | 2. Check the list of databases using the `show dbs` command. 9 | 10 | --- 11 | 12 | ### **Example: Create a Database and Check the List** 13 | 14 | ```javascript 15 | // Step 1: Switch to or create a database named 'myDatabase' 16 | use myDatabase; 17 | 18 | // Step 2: Check the list of all databases 19 | show dbs; 20 | ``` 21 | 22 | --- 23 | -------------------------------------------------------------------------------- /08 MongoDB mongosh Create Collection.md: -------------------------------------------------------------------------------- 1 | # MongoDB mongosh Create Collection 2 | 3 | --- 4 | 5 | ### **Step-by-Step Guide to Create a Collection** 6 | 7 | #### **Step 1: Start MongoDB Shell** 8 | 1. Open your terminal or command prompt. 9 | 2. Start `mongosh` by typing: 10 | ```bash 11 | mongosh 12 | ``` 13 | 14 | #### **Step 2: Switch to the Database** 15 | 1. Use the `use ` command to select or create a database. 16 | ```javascript 17 | use myDatabase 18 | ``` 19 | - If the database doesn't exist, MongoDB will create it when you add data or explicitly create a collection. 20 | 21 | #### **Step 3: Create a Collection** 22 | 1. Use the `createCollection` method to create a collection explicitly. 23 | ```javascript 24 | db.createCollection("myCollection"); 25 | ``` 26 | - Replace `"myCollection"` with your desired collection name. 27 | 28 | #### **Step 4: Verify the Collection** 29 | 1. Use the `show collections` command to list all collections in the database. 30 | ```javascript 31 | show collections 32 | ``` 33 | 34 | --- 35 | 36 | ### **Example** 37 | Here’s a complete session in **mongosh**: 38 | 39 | ```javascript 40 | // Step 1: Switch to a database 41 | use myDatabase; 42 | 43 | // Step 2: Create a collection named 'students' 44 | db.createCollection("students"); 45 | 46 | // Step 3: Verify the collection 47 | show collections; 48 | ``` 49 | 50 | --- 51 | 52 | ### **Expected Output** 53 | After running the above commands, you should see the following: 54 | 55 | 1. When creating the collection: 56 | ```text 57 | { ok: 1 } 58 | ``` 59 | 2. When listing collections: 60 | ```text 61 | students 62 | ``` 63 | 64 | --- 65 | 66 | ### **Important Notes** 67 | - **Automatic Collection Creation:** If you insert a document into a non-existing collection, MongoDB will create the collection for you automatically. 68 | - **Explicit Creation:** Use `createCollection` only if you need to configure options or want to ensure the collection exists before inserting data. 69 | 70 | This simple process helps you explicitly create and manage collections in MongoDB! 71 | 72 | -------------------------------------------------------------------------------- /09 MongoDB mongosh Insert.md: -------------------------------------------------------------------------------- 1 | # MongoDB mongosh Insert 2 | 3 | Inserting documents into a MongoDB collection using `mongosh` (MongoDB Shell) is a straightforward process. Here's a step-by-step guide to help you insert documents into a collection. 4 | 5 | ### Step-by-Step Guide: Inserting Documents Using `mongosh` 6 | 7 | #### Prerequisites 8 | 9 | 1. **MongoDB Server**: Ensure that MongoDB is installed and running on your machine. You can download MongoDB from the [MongoDB official website](https://www.mongodb.com/try/download/community). 10 | 2. **MongoDB Shell (`mongosh`)**: Ensure that `mongosh` is installed. You can download it from the [MongoDB Shell download page](https://www.mongodb.com/try/download/shell). 11 | 12 | #### Step 1: Start the MongoDB Server 13 | 14 | Make sure your MongoDB server is running. Open a terminal and start the MongoDB server by typing: 15 | 16 | ```sh 17 | mongod 18 | ``` 19 | 20 | Leave this terminal window open as the MongoDB server needs to be running in the background. 21 | 22 | #### Step 2: Open MongoDB Shell (`mongosh`) 23 | 24 | Open a new terminal window and start the MongoDB Shell by typing: 25 | 26 | ```sh 27 | mongosh 28 | ``` 29 | 30 | You will see output similar to this: 31 | 32 | ```sh 33 | Current Mongosh Log ID: 60b6e0a... 34 | Connecting to: mongodb://localhost:27017 35 | MongoDB server version: 4.4.6 36 | ``` 37 | 38 | #### Step 3: Switch to the Database 39 | 40 | Switch to the database where you want to insert documents. If the database doesn't exist, it will be created when you switch to it. For example, to switch to a database named `codeswithpankaj`, type: 41 | 42 | ```sh 43 | use codeswithpankaj 44 | ``` 45 | 46 | You should see a message indicating that you've switched to the new database: 47 | 48 | ```sh 49 | switched to db codeswithpankaj 50 | ``` 51 | 52 | #### Step 4: Insert a Single Document 53 | 54 | To insert a single document into a collection, use the `insertOne` method. If the collection doesn't exist, it will be created when you insert the document. For example, to insert a document into a collection named `users`, type: 55 | 56 | ```sh 57 | db.users.insertOne({ name: "Pankaj", age: 30, email: "pankaj@example.com" }) 58 | ``` 59 | 60 | You should see a confirmation message like this: 61 | 62 | ```sh 63 | { 64 | acknowledged: true, 65 | insertedId: ObjectId("60b6e0a...") 66 | } 67 | ``` 68 | 69 | #### Step 5: Insert Multiple Documents 70 | 71 | To insert multiple documents into a collection, use the `insertMany` method. For example, to insert multiple documents into the `users` collection, type: 72 | 73 | ```sh 74 | db.users.insertMany([ 75 | { name: "John", age: 25, email: "john@example.com" }, 76 | { name: "Jane", age: 28, email: "jane@example.com" } 77 | ]) 78 | ``` 79 | 80 | You should see a confirmation message like this: 81 | 82 | ```sh 83 | { 84 | acknowledged: true, 85 | insertedIds: [ 86 | ObjectId("60b6e0a..."), 87 | ObjectId("60b6e0b...") 88 | ] 89 | } 90 | ``` 91 | 92 | #### Step 6: Verify the Insertions 93 | 94 | To verify that your documents were inserted, you can query the collection using the `find` method. For example, to find all documents in the `users` collection, type: 95 | 96 | ```sh 97 | db.users.find().pretty() 98 | ``` 99 | 100 | You should see the inserted documents: 101 | 102 | ```sh 103 | [ 104 | { _id: ObjectId("60b6e0a..."), name: "Pankaj", age: 30, email: "pankaj@example.com" }, 105 | { _id: ObjectId("60b6e0b..."), name: "John", age: 25, email: "john@example.com" }, 106 | { _id: ObjectId("60b6e0c..."), name: "Jane", age: 28, email: "jane@example.com" } 107 | ] 108 | ``` 109 | 110 | ### Summary 111 | 112 | Congratulations! You have successfully inserted documents into a MongoDB collection using `mongosh`. 113 | 114 | In summary, the steps are: 115 | 1. Ensure the MongoDB server is running. 116 | 2. Open `mongosh`. 117 | 3. Use the `use` command to switch to the desired database. 118 | 4. Insert a single document using `insertOne`. 119 | 5. Insert multiple documents using `insertMany`. 120 | 6. Verify the insertions using `find`. 121 | 122 | -------------------------------------------------------------------------------- /10 MongoDB mongosh Find.md: -------------------------------------------------------------------------------- 1 | # MongoDB mongosh Find 2 | 3 | In MongoDB, the `find` method is used to query and retrieve documents from a collection in **mongosh**. It allows you to specify filter criteria and project specific fields from the documents. 4 | 5 | --- 6 | 7 | ### **Syntax** 8 | ```javascript 9 | db.collection.find(query, projection); 10 | ``` 11 | 12 | - **`query`**: A document specifying selection criteria (optional). If omitted, all documents in the collection are returned. 13 | - **`projection`**: A document specifying which fields to include or exclude (optional). 14 | 15 | --- 16 | 17 | ### **Step-by-Step Guide to Use `find`** 18 | 19 | #### **Step 1: Insert Sample Data** 20 | Before using `find`, make sure the collection has some data. 21 | 22 | ```javascript 23 | // Switch to a database 24 | use myDatabase; 25 | 26 | // Insert sample documents into the 'students' collection 27 | db.students.insertMany([ 28 | { name: "Alice", age: 22, grade: "A" }, 29 | { name: "Bob", age: 25, grade: "B" }, 30 | { name: "Charlie", age: 23, grade: "A" }, 31 | { name: "Diana", age: 24, grade: "C" } 32 | ]); 33 | ``` 34 | 35 | --- 36 | 37 | #### **Step 2: Use `find` to Query Documents** 38 | 39 | 1. **Retrieve All Documents** 40 | ```javascript 41 | db.students.find(); 42 | ``` 43 | **Output:** 44 | ```json 45 | { "_id": ObjectId("..."), "name": "Alice", "age": 22, "grade": "A" } 46 | { "_id": ObjectId("..."), "name": "Bob", "age": 25, "grade": "B" } 47 | { "_id": ObjectId("..."), "name": "Charlie", "age": 23, "grade": "A" } 48 | { "_id": ObjectId("..."), "name": "Diana", "age": 24, "grade": "C" } 49 | ``` 50 | 51 | 2. **Filter by a Specific Field** 52 | Retrieve all students with a grade of "A": 53 | ```javascript 54 | db.students.find({ grade: "A" }); 55 | ``` 56 | 57 | 3. **Retrieve Specific Fields** 58 | Retrieve only the `name` and `age` fields: 59 | ```javascript 60 | db.students.find({}, { name: 1, age: 1, _id: 0 }); 61 | ``` 62 | **Output:** 63 | ```json 64 | { "name": "Alice", "age": 22 } 65 | { "name": "Bob", "age": 25 } 66 | { "name": "Charlie", "age": 23 } 67 | { "name": "Diana", "age": 24 } 68 | ``` 69 | 70 | 4. **Use Comparison Operators** 71 | Retrieve students older than 23: 72 | ```javascript 73 | db.students.find({ age: { $gt: 23 } }); 74 | ``` 75 | 76 | 5. **Combine Conditions** 77 | Retrieve students with grade "A" and age less than 23: 78 | ```javascript 79 | db.students.find({ grade: "A", age: { $lt: 23 } }); 80 | ``` 81 | 82 | 6. **Sort Results** 83 | Sort students by age in descending order: 84 | ```javascript 85 | db.students.find().sort({ age: -1 }); 86 | ``` 87 | 88 | --- 89 | 90 | ### **Common Query Operators** 91 | - `$eq`: Equal to a value. 92 | - `$ne`: Not equal to a value. 93 | - `$gt`: Greater than a value. 94 | - `$gte`: Greater than or equal to a value. 95 | - `$lt`: Less than a value. 96 | - `$lte`: Less than or equal to a value. 97 | - `$in`: Matches any value in an array. 98 | - `$or`: Combines multiple conditions with OR logic. 99 | - `$and`: Combines multiple conditions with AND logic. 100 | 101 | --- 102 | 103 | # How to use MongoDB's common query operators in **mongosh**: 104 | 105 | --- 106 | 107 | ### **Sample Data** 108 | Let's use a collection named `products` with the following documents: 109 | 110 | ```javascript 111 | use myDatabase; 112 | 113 | db.products.insertMany([ 114 | { name: "Laptop", price: 800, category: "Electronics", stock: 10 }, 115 | { name: "Phone", price: 600, category: "Electronics", stock: 25 }, 116 | { name: "Tablet", price: 300, category: "Electronics", stock: 15 }, 117 | { name: "Chair", price: 100, category: "Furniture", stock: 50 }, 118 | { name: "Desk", price: 200, category: "Furniture", stock: 20 }, 119 | { name: "Lamp", price: 50, category: "Furniture", stock: 30 } 120 | ]); 121 | ``` 122 | 123 | --- 124 | 125 | ### **Query Examples** 126 | 127 | #### **1. `$eq`: Equal to a value** 128 | Find all products in the "Electronics" category: 129 | ```javascript 130 | db.products.find({ category: { $eq: "Electronics" } }); 131 | ``` 132 | 133 | #### **2. `$ne`: Not equal to a value** 134 | Find all products that are not in the "Furniture" category: 135 | ```javascript 136 | db.products.find({ category: { $ne: "Furniture" } }); 137 | ``` 138 | 139 | #### **3. `$gt`: Greater than a value** 140 | Find all products with a price greater than 500: 141 | ```javascript 142 | db.products.find({ price: { $gt: 500 } }); 143 | ``` 144 | 145 | #### **4. `$gte`: Greater than or equal to a value** 146 | Find all products with a price greater than or equal to 300: 147 | ```javascript 148 | db.products.find({ price: { $gte: 300 } }); 149 | ``` 150 | 151 | #### **5. `$lt`: Less than a value** 152 | Find all products with stock less than 20: 153 | ```javascript 154 | db.products.find({ stock: { $lt: 20 } }); 155 | ``` 156 | 157 | #### **6. `$lte`: Less than or equal to a value** 158 | Find all products with a price less than or equal to 100: 159 | ```javascript 160 | db.products.find({ price: { $lte: 100 } }); 161 | ``` 162 | 163 | #### **7. `$in`: Matches any value in an array** 164 | Find all products in either the "Electronics" or "Furniture" category: 165 | ```javascript 166 | db.products.find({ category: { $in: ["Electronics", "Furniture"] } }); 167 | ``` 168 | 169 | #### **8. `$or`: Combines multiple conditions with OR logic** 170 | Find all products with a price greater than 500 **OR** stock less than 20: 171 | ```javascript 172 | db.products.find({ 173 | $or: [ 174 | { price: { $gt: 500 } }, 175 | { stock: { $lt: 20 } } 176 | ] 177 | }); 178 | ``` 179 | 180 | #### **9. `$and`: Combines multiple conditions with AND logic** 181 | Find all products in the "Electronics" category **AND** with a price less than 800: 182 | ```javascript 183 | db.products.find({ 184 | $and: [ 185 | { category: "Electronics" }, 186 | { price: { $lt: 800 } } 187 | ] 188 | }); 189 | ``` 190 | 191 | --- 192 | 193 | ### **Result Examples** 194 | **For `$or`:** 195 | ```json 196 | { "_id": ObjectId("..."), "name": "Laptop", "price": 800, "category": "Electronics", "stock": 10 } 197 | { "_id": ObjectId("..."), "name": "Tablet", "price": 300, "category": "Electronics", "stock": 15 } 198 | { "_id": ObjectId("..."), "name": "Chair", "price": 100, "category": "Furniture", "stock": 50 } 199 | { "_id": ObjectId("..."), "name": "Lamp", "price": 50, "category": "Furniture", "stock": 30 } 200 | ``` 201 | 202 | This demonstrates how to use these operators effectively in your queries. 203 | -------------------------------------------------------------------------------- /11 MongoDB mongosh Update.md: -------------------------------------------------------------------------------- 1 | # MongoDB mongosh Update 2 | 3 | --- 4 | 5 | ### **Update Methods** 6 | 1. **`updateOne()`**: Updates the first document that matches the filter. 7 | 2. **`updateMany()`**: Updates all documents that match the filter. 8 | 3. **`replaceOne()`**: Replaces an entire document with a new one. 9 | 10 | --- 11 | 12 | ### **Syntax** 13 | 14 | #### **`updateOne`** 15 | ```javascript 16 | db.collection.updateOne(filter, update, options); 17 | ``` 18 | 19 | #### **`updateMany`** 20 | ```javascript 21 | db.collection.updateMany(filter, update, options); 22 | ``` 23 | 24 | #### **`replaceOne`** 25 | ```javascript 26 | db.collection.replaceOne(filter, replacement, options); 27 | ``` 28 | 29 | - **`filter`**: Specifies the criteria to match documents. 30 | - **`update`**: Specifies the update operations to apply. 31 | - **`replacement`**: A new document to replace the existing one (for `replaceOne`). 32 | - **`options`**: Optional parameters (e.g., `upsert` to insert a new document if no match is found). 33 | 34 | --- 35 | 36 | ### **Example: Update in MongoDB** 37 | 38 | #### **Sample Data** 39 | ```javascript 40 | db.products.insertMany([ 41 | { name: "Laptop", price: 800, category: "Electronics", stock: 10 }, 42 | { name: "Phone", price: 600, category: "Electronics", stock: 25 }, 43 | { name: "Chair", price: 100, category: "Furniture", stock: 50 } 44 | ]); 45 | ``` 46 | 47 | --- 48 | 49 | #### **1. Update a Single Document (`updateOne`)** 50 | Increase the stock of the "Laptop" by 5: 51 | ```javascript 52 | db.products.updateOne( 53 | { name: "Laptop" }, // Filter 54 | { $inc: { stock: 5 } } // Update operation 55 | ); 56 | ``` 57 | 58 | **Result:** 59 | ```json 60 | { "acknowledged": true, "matchedCount": 1, "modifiedCount": 1 } 61 | ``` 62 | 63 | --- 64 | 65 | #### **2. Update Multiple Documents (`updateMany`)** 66 | Change the category of all products with a price greater than 500 to "Premium Electronics": 67 | ```javascript 68 | db.products.updateMany( 69 | { price: { $gt: 500 } }, // Filter 70 | { $set: { category: "Premium Electronics" } } // Update operation 71 | ); 72 | ``` 73 | 74 | **Result:** 75 | ```json 76 | { "acknowledged": true, "matchedCount": 2, "modifiedCount": 2 } 77 | ``` 78 | 79 | --- 80 | 81 | #### **3. Replace a Document (`replaceOne`)** 82 | Replace the document for "Chair" with a new one: 83 | ```javascript 84 | db.products.replaceOne( 85 | { name: "Chair" }, // Filter 86 | { name: "Armchair", price: 150, category: "Furniture", stock: 30 } // Replacement document 87 | ); 88 | ``` 89 | 90 | **Result:** 91 | ```json 92 | { "acknowledged": true, "matchedCount": 1, "modifiedCount": 1 } 93 | ``` 94 | 95 | --- 96 | 97 | #### **4. Upsert Option** 98 | If no document matches, insert a new document: 99 | ```javascript 100 | db.products.updateOne( 101 | { name: "Tablet" }, // Filter 102 | { $set: { price: 300, category: "Electronics", stock: 15 } }, // Update operation 103 | { upsert: true } // Option 104 | ); 105 | ``` 106 | 107 | **Result:** 108 | If the document doesn't exist, it will be created. 109 | 110 | --- 111 | 112 | #### **5. Update with Multiple Operations** 113 | Perform multiple updates in a single operation: 114 | ```javascript 115 | db.products.updateOne( 116 | { name: "Laptop" }, 117 | { 118 | $set: { price: 850 }, // Set a new price 119 | $inc: { stock: 2 } // Increase stock by 2 120 | } 121 | ); 122 | ``` 123 | 124 | --- 125 | 126 | ### **Common Update Operators** 127 | - `$set`: Set the value of a field. 128 | - `$unset`: Remove a field. 129 | - `$inc`: Increment a field by a value. 130 | - `$mul`: Multiply a field by a value. 131 | - `$rename`: Rename a field. 132 | - `$min`: Update a field only if the new value is less than the current value. 133 | - `$max`: Update a field only if the new value is greater than the current value. 134 | 135 | --- 136 | 137 | ### **Verify the Updates** 138 | You can check the updated documents using: 139 | ```javascript 140 | db.products.find().pretty(); 141 | ``` 142 | 143 | # Common update operators** using the `updateOne` and `updateMany` methods in **mongosh**. 144 | 145 | --- 146 | 147 | ### **Sample Data** 148 | Insert the following sample data into a collection named `employees`: 149 | ```javascript 150 | db.employees.insertMany([ 151 | { name: "Alice", age: 25, salary: 5000, department: "HR" }, 152 | { name: "Bob", age: 30, salary: 6000, department: "Engineering" }, 153 | { name: "Charlie", age: 35, salary: 7000, department: "Sales" } 154 | ]); 155 | ``` 156 | 157 | --- 158 | 159 | ### **Examples** 160 | 161 | #### **1. `$set`: Set the value of a field** 162 | Update Bob's department to "Product Management": 163 | ```javascript 164 | db.employees.updateOne( 165 | { name: "Bob" }, // Filter 166 | { $set: { department: "Product Management" } } // Update operation 167 | ); 168 | ``` 169 | 170 | --- 171 | 172 | #### **2. `$unset`: Remove a field** 173 | Remove the `age` field from Alice's document: 174 | ```javascript 175 | db.employees.updateOne( 176 | { name: "Alice" }, // Filter 177 | { $unset: { age: "" } } // Update operation 178 | ); 179 | ``` 180 | 181 | --- 182 | 183 | #### **3. `$inc`: Increment a field by a value** 184 | Increase Charlie's salary by 1000: 185 | ```javascript 186 | db.employees.updateOne( 187 | { name: "Charlie" }, // Filter 188 | { $inc: { salary: 1000 } } // Update operation 189 | ); 190 | ``` 191 | 192 | --- 193 | 194 | #### **4. `$mul`: Multiply a field by a value** 195 | Double Bob's salary: 196 | ```javascript 197 | db.employees.updateOne( 198 | { name: "Bob" }, // Filter 199 | { $mul: { salary: 2 } } // Update operation 200 | ); 201 | ``` 202 | 203 | --- 204 | 205 | #### **5. `$rename`: Rename a field** 206 | Rename the `department` field to `team` for all employees: 207 | ```javascript 208 | db.employees.updateMany( 209 | {}, // Filter (all documents) 210 | { $rename: { department: "team" } } // Update operation 211 | ); 212 | ``` 213 | 214 | --- 215 | 216 | #### **6. `$min`: Update a field only if the new value is less than the current value** 217 | Set Alice's salary to 4500, but only if it's less than the current value: 218 | ```javascript 219 | db.employees.updateOne( 220 | { name: "Alice" }, // Filter 221 | { $min: { salary: 4500 } } // Update operation 222 | ); 223 | ``` 224 | 225 | --- 226 | 227 | #### **7. `$max`: Update a field only if the new value is greater than the current value** 228 | Set Charlie's salary to 8000, but only if it's greater than the current value: 229 | ```javascript 230 | db.employees.updateOne( 231 | { name: "Charlie" }, // Filter 232 | { $max: { salary: 8000 } } // Update operation 233 | ); 234 | ``` 235 | 236 | --- 237 | 238 | ### **Verify the Updates** 239 | After running the above commands, you can view the updated documents: 240 | ```javascript 241 | db.employees.find().pretty(); 242 | ``` 243 | 244 | --- 245 | 246 | ### **Expected Results** 247 | 248 | **Before Updates:** 249 | ```json 250 | { "_id": ..., "name": "Alice", "age": 25, "salary": 5000, "department": "HR" } 251 | { "_id": ..., "name": "Bob", "age": 30, "salary": 6000, "department": "Engineering" } 252 | { "_id": ..., "name": "Charlie", "age": 35, "salary": 7000, "department": "Sales" } 253 | ``` 254 | 255 | **After Updates:** 256 | ```json 257 | { "_id": ..., "name": "Alice", "salary": 4500, "team": "HR" } 258 | { "_id": ..., "name": "Bob", "salary": 12000, "team": "Product Management" } 259 | { "_id": ..., "name": "Charlie", "salary": 8000, "team": "Sales" } 260 | ``` 261 | 262 | -------------------------------------------------------------------------------- /12 MongoDB mongosh Delete.md: -------------------------------------------------------------------------------- 1 | # MongoDB mongosh Delete 2 | 3 | In MongoDB, you can use the `deleteOne` or `deleteMany` methods in the `mongosh` shell to remove documents from a collection based on specified criteria. Here's how you can use these methods: 4 | 5 | ### Delete a Single Document: 6 | 7 | ```javascript 8 | // Switch to the desired database (optional) 9 | use mydatabase 10 | 11 | // Delete a single document from a collection 12 | db.myCollection.deleteOne({ key: value }) 13 | ``` 14 | 15 | Replace "mydatabase" with the name of your database and "myCollection" with the name of your collection. Adjust the filter criteria to match the document you want to delete. 16 | 17 | ### Delete Multiple Documents: 18 | 19 | ```javascript 20 | // Delete multiple documents from a collection 21 | db.myCollection.deleteMany({ key: value }) 22 | ``` 23 | 24 | This is similar to `deleteOne`, but it deletes multiple documents that match the filter criteria. 25 | 26 | ### Delete All Documents in a Collection: 27 | 28 | ```javascript 29 | // Delete all documents from a collection 30 | db.myCollection.deleteMany({}) 31 | ``` 32 | 33 | Be cautious when using this command, as it will remove all documents from the specified collection. 34 | 35 | ### Verify Deletion: 36 | 37 | After performing a deletion, you can verify the changes by querying the collection: 38 | 39 | ```javascript 40 | // Find remaining documents in the collection 41 | db.myCollection.find({}) 42 | ``` 43 | 44 | Remember to adjust the code snippets based on your specific use case and data model. Deleting documents is a powerful operation, so use it with care. Always ensure that you have a backup or are working with test data when performing delete operations. 45 | -------------------------------------------------------------------------------- /13 MongoDB Query Operators.md: -------------------------------------------------------------------------------- 1 | # MongoDB Query Operators 2 | 3 | MongoDB provides a variety of query operators that you can use to perform complex queries on your data. Here are some commonly used query operators: 4 | 5 | ### Comparison Operators: 6 | 7 | 1. **Equality (`$eq`):** 8 | - Matches values that are equal to a specified value. 9 | 10 | ```javascript 11 | { field: { $eq: value } } 12 | ``` 13 | 14 | 2. **Inequality (`$ne`):** 15 | - Matches values that are not equal to a specified value. 16 | 17 | ```javascript 18 | { field: { $ne: value } } 19 | ``` 20 | 21 | 3. **Greater Than (`$gt`), Less Than (`$lt`), Greater Than or Equal To (`$gte`), Less Than or Equal To (`$lte`):** 22 | - Matches values based on comparison. 23 | 24 | ```javascript 25 | { field: { $gt: value } } 26 | { field: { $lt: value } } 27 | { field: { $gte: value } } 28 | { field: { $lte: value } } 29 | ``` 30 | 31 | ### Logical Operators: 32 | 33 | 1. **Logical AND (`$and`):** 34 | - Joins query clauses with a logical AND. 35 | 36 | ```javascript 37 | { $and: [ { condition1 }, { condition2 } ] } 38 | ``` 39 | 40 | 2. **Logical OR (`$or`):** 41 | - Joins query clauses with a logical OR. 42 | 43 | ```javascript 44 | { $or: [ { condition1 }, { condition2 } ] } 45 | ``` 46 | 47 | 3. **Logical NOT (`$not`):** 48 | - Inverts the effect of a query expression. 49 | 50 | ```javascript 51 | { field: { $not: { $eq: value } } } 52 | ``` 53 | 54 | ### Element Operators: 55 | 56 | 1. **Exists (`$exists`):** 57 | - Matches documents that have the specified field. 58 | 59 | ```javascript 60 | { field: { $exists: true } } 61 | ``` 62 | 63 | 2. **Type (`$type`):** 64 | - Selects documents if a field is of the specified type. 65 | 66 | ```javascript 67 | { field: { $type: "string" } } 68 | ``` 69 | 70 | ### Array Operators: 71 | 72 | 1. **Element Match (`$elemMatch`):** 73 | - Selects documents if an array field contains at least one element that matches all the specified query criteria. 74 | 75 | ```javascript 76 | { arrayField: { $elemMatch: { condition1, condition2 } } } 77 | ``` 78 | 79 | 2. **Size (`$size`):** 80 | - Matches documents where the array field is a specified size. 81 | 82 | ```javascript 83 | { arrayField: { $size: size } } 84 | ``` 85 | 86 | ### Evaluation Operators: 87 | 88 | 1. **Modulus (`$mod`):** 89 | - Performs a modulo operation on the value of a field and selects documents with a specified result. 90 | 91 | ```javascript 92 | { field: { $mod: [ divisor, remainder ] } } 93 | ``` 94 | 95 | 2. **Type (`$type`):** 96 | - Selects documents if a field is of the specified BSON data type. 97 | 98 | ```javascript 99 | { field: { $type: "string" } } 100 | ``` 101 | 102 | These are just a few examples of the many query operators available in MongoDB. You can combine and nest these operators to build complex queries that suit your data retrieval needs. For more details, refer to the official documentation: [MongoDB Query and Projection Operators](https://docs.mongodb.com/manual/reference/operator/query/). 103 | -------------------------------------------------------------------------------- /14 MongoDB Update Operators.md: -------------------------------------------------------------------------------- 1 | # MongoDB Update Operators 2 | 3 | MongoDB provides update operators that you can use to modify the contents of documents in a collection. Here are some commonly used update operators: 4 | 5 | ### `$set` Operator: 6 | 7 | The `$set` operator updates the value of a field in a document. If the field does not exist, `$set` will create it. 8 | 9 | ```javascript 10 | db.collection.updateOne({ _id: 1 }, { $set: { key: newValue } }) 11 | ``` 12 | 13 | ### `$unset` Operator: 14 | 15 | The `$unset` operator removes the specified field from a document. 16 | 17 | ```javascript 18 | db.collection.updateOne({ _id: 1 }, { $unset: { key: 1 } }) 19 | ``` 20 | 21 | ### `$inc` Operator: 22 | 23 | The `$inc` operator increments the value of the specified field by a certain amount. 24 | 25 | ```javascript 26 | db.collection.updateOne({ _id: 1 }, { $inc: { key: 5 } }) 27 | ``` 28 | 29 | ### `$mul` Operator: 30 | 31 | The `$mul` operator multiplies the value of the specified field by a certain amount. 32 | 33 | ```javascript 34 | db.collection.updateOne({ _id: 1 }, { $mul: { key: 2 } }) 35 | ``` 36 | 37 | ### `$rename` Operator: 38 | 39 | The `$rename` operator renames a field in a document. 40 | 41 | ```javascript 42 | db.collection.updateOne({ _id: 1 }, { $rename: { oldKey: "newKey" } }) 43 | ``` 44 | 45 | ### `$min` and `$max` Operators: 46 | 47 | The `$min` operator updates the value of the specified field to a specified value if the specified value is less than the current value. 48 | 49 | ```javascript 50 | db.collection.updateOne({ _id: 1 }, { $min: { key: minValue } }) 51 | ``` 52 | 53 | The `$max` operator updates the value of the specified field to a specified value if the specified value is greater than the current value. 54 | 55 | ```javascript 56 | db.collection.updateOne({ _id: 1 }, { $max: { key: maxValue } }) 57 | ``` 58 | 59 | ### `$currentDate` Operator: 60 | 61 | The `$currentDate` operator sets the value of a field to the current date or timestamp. 62 | 63 | ```javascript 64 | db.collection.updateOne({ _id: 1 }, { $currentDate: { key: true } }) 65 | ``` 66 | 67 | These are just a few examples of MongoDB update operators. You can use these operators individually or combine them to perform complex updates on your documents. For more details, refer to the official documentation: [MongoDB Update Operators](https://docs.mongodb.com/manual/reference/operator/update/). 68 | -------------------------------------------------------------------------------- /15 MongoDB Aggregation Pipelines.md: -------------------------------------------------------------------------------- 1 | # MongoDB Aggregation Pipelines 2 | 3 | MongoDB Aggregation Pipeline is a powerful framework for data transformation within MongoDB. It allows you to process and transform documents in a collection through a sequence of stages, each representing a specific operation. Aggregation pipelines are typically used for tasks like filtering, sorting, grouping, and performing various transformations on the data. 4 | 5 | Here are some common stages used in MongoDB Aggregation Pipelines: 6 | 7 | ### 1. `$match` Stage: 8 | 9 | The `$match` stage filters documents based on specified criteria. 10 | 11 | ```javascript 12 | db.collection.aggregate([ 13 | { $match: { field: value } } 14 | ]) 15 | ``` 16 | 17 | ### 2. `$project` Stage: 18 | 19 | The `$project` stage reshapes documents by specifying which fields to include or exclude. 20 | 21 | ```javascript 22 | db.collection.aggregate([ 23 | { $project: { newField1: "$oldField1", newField2: 1, _id: 0 } } 24 | ]) 25 | ``` 26 | 27 | ### 3. `$group` Stage: 28 | 29 | The `$group` stage groups documents by a specified key and applies aggregate functions. 30 | 31 | ```javascript 32 | db.collection.aggregate([ 33 | { $group: { _id: "$field", total: { $sum: "$quantity" } } } 34 | ]) 35 | ``` 36 | 37 | ### 4. `$sort` Stage: 38 | 39 | The `$sort` stage sorts documents based on specified fields and order. 40 | 41 | ```javascript 42 | db.collection.aggregate([ 43 | { $sort: { field: 1 } } 44 | ]) 45 | ``` 46 | 47 | ### 5. `$limit` and `$skip` Stages: 48 | 49 | The `$limit` stage restricts the number of documents passed to the next stage, and `$skip` skips a specified number of documents. 50 | 51 | ```javascript 52 | db.collection.aggregate([ 53 | { $limit: 10 }, 54 | { $skip: 5 } 55 | ]) 56 | ``` 57 | 58 | ### 6. `$unwind` Stage: 59 | 60 | The `$unwind` stage deconstructs an array field, creating a separate document for each element. 61 | 62 | ```javascript 63 | db.collection.aggregate([ 64 | { $unwind: "$arrayField" } 65 | ]) 66 | ``` 67 | 68 | ### 7. `$lookup` Stage: 69 | 70 | The `$lookup` stage performs a left outer join with another collection. 71 | 72 | ```javascript 73 | db.orders.aggregate([ 74 | { 75 | $lookup: 76 | { 77 | from: "products", 78 | localField: "productId", 79 | foreignField: "_id", 80 | as: "productDetails" 81 | } 82 | } 83 | ]) 84 | ``` 85 | 86 | ### 8. `$facet` Stage: 87 | 88 | The `$facet` stage enables the parallel execution of multiple pipelines. 89 | 90 | ```javascript 91 | db.collection.aggregate([ 92 | { 93 | $facet: { 94 | "facet1": [ /* pipeline 1 */ ], 95 | "facet2": [ /* pipeline 2 */ ] 96 | } 97 | } 98 | ]) 99 | ``` 100 | 101 | These are just a few examples of the many stages available in MongoDB Aggregation Pipelines. You can combine and use these stages to perform complex data transformations and analytics on your MongoDB data. For more details, refer to the official documentation: [MongoDB Aggregation](https://docs.mongodb.com/manual/aggregation/). 102 | 103 | 104 | ### 1. `$group`: 105 | 106 | The `$group` stage groups documents by a specified key and allows you to perform aggregate functions on grouped data. 107 | 108 | ```javascript 109 | db.collection.aggregate([ 110 | { $group: { _id: "$field", count: { $sum: 1 } } } 111 | ]) 112 | ``` 113 | 114 | ### 2. `$limit`: 115 | 116 | The `$limit` stage restricts the number of documents passed to the next stage. 117 | 118 | ```javascript 119 | db.collection.aggregate([ 120 | { $limit: 10 } 121 | ]) 122 | ``` 123 | 124 | ### 3. `$project`: 125 | 126 | The `$project` stage reshapes documents by specifying which fields to include or exclude. 127 | 128 | ```javascript 129 | db.collection.aggregate([ 130 | { $project: { newField1: "$oldField1", newField2: 1, _id: 0 } } 131 | ]) 132 | ``` 133 | 134 | ### 4. `$sort`: 135 | 136 | The `$sort` stage sorts documents based on specified fields and order. 137 | 138 | ```javascript 139 | db.collection.aggregate([ 140 | { $sort: { field: 1 } } 141 | ]) 142 | ``` 143 | 144 | ### 5. `$match`: 145 | 146 | The `$match` stage filters documents based on specified criteria. 147 | 148 | ```javascript 149 | db.collection.aggregate([ 150 | { $match: { field: value } } 151 | ]) 152 | ``` 153 | 154 | ### 6. `$addFields`: 155 | 156 | The `$addFields` stage adds new fields to documents or overwrites existing fields. 157 | 158 | ```javascript 159 | db.collection.aggregate([ 160 | { $addFields: { newField: "value" } } 161 | ]) 162 | ``` 163 | 164 | ### 7. `$count`: 165 | 166 | The `$count` stage returns the total number of documents in the aggregation pipeline. 167 | 168 | ```javascript 169 | db.collection.aggregate([ 170 | { $count: "documentCount" } 171 | ]) 172 | ``` 173 | 174 | ### 8. `$lookup`: 175 | 176 | The `$lookup` stage performs a left outer join with another collection. 177 | 178 | ```javascript 179 | db.orders.aggregate([ 180 | { 181 | $lookup: { 182 | from: "products", 183 | localField: "productId", 184 | foreignField: "_id", 185 | as: "productDetails" 186 | } 187 | } 188 | ]) 189 | ``` 190 | 191 | ### 9. `$out`: 192 | 193 | The `$out` stage writes the result of the aggregation pipeline to a specified collection. 194 | 195 | ```javascript 196 | db.collection.aggregate([ 197 | { $out: "newCollection" } 198 | ]) 199 | ``` 200 | -------------------------------------------------------------------------------- /16 Indexing & Search.md: -------------------------------------------------------------------------------- 1 | 2 | # Indexing and Search 3 | 4 | In MongoDB, indexing is a crucial feature for optimizing query performance, especially when dealing with large amounts of data. Indexes help MongoDB efficiently locate and retrieve documents that match specific criteria. Additionally, MongoDB provides various features for searching and querying data. Let's explore indexing and search-related concepts: 5 | 6 | ### Indexing in MongoDB: 7 | 8 | 1. **Creating an Index:** 9 | - You can create an index on a specific field to speed up queries on that field. 10 | 11 | ```javascript 12 | db.collection.createIndex({ field: 1 }) 13 | ``` 14 | 15 | Replace "collection" with your collection name and "field" with the field on which you want to create an index. The value "1" indicates an ascending index, and "-1" indicates a descending index. 16 | 17 | 2. **Compound Index:** 18 | - Compound indexes are created on multiple fields to optimize queries that involve those fields. 19 | 20 | ```javascript 21 | db.collection.createIndex({ field1: 1, field2: -1 }) 22 | ``` 23 | 24 | This creates a compound index on `field1` in ascending order and `field2` in descending order. 25 | 26 | 3. **Text Index:** 27 | - Text indexes are used for full-text searches on string content. 28 | 29 | ```javascript 30 | db.collection.createIndex({ textField: "text" }) 31 | ``` 32 | 33 | After creating a text index, you can perform text searches using the `$text` operator. 34 | 35 | ### Search in MongoDB: 36 | 37 | 1. **Basic Queries:** 38 | - Use `find()` to perform basic queries. 39 | 40 | ```javascript 41 | db.collection.find({ field: value }) 42 | ``` 43 | 44 | 2. **Text Search:** 45 | - Utilize the `$text` operator for text searches on fields with a text index. 46 | 47 | ```javascript 48 | db.collection.find({ $text: { $search: "keyword" } }) 49 | ``` 50 | 51 | 3. **Regular Expressions:** 52 | - MongoDB supports regular expressions for pattern matching. 53 | 54 | ```javascript 55 | db.collection.find({ field: /pattern/ }) 56 | ``` 57 | 58 | 4. **Case-Insensitive Search:** 59 | - Use the `$regex` operator with the `$options` modifier for case-insensitive searches. 60 | 61 | ```javascript 62 | db.collection.find({ field: { $regex: /pattern/i } }) 63 | ``` 64 | 65 | 5. **Sorting:** 66 | - Sort query results using the `sort()` method. 67 | 68 | ```javascript 69 | db.collection.find().sort({ field: 1 }) 70 | ``` 71 | 72 | 6. **Limit and Skip:** 73 | - Use `limit()` and `skip()` to control the number of returned documents. 74 | 75 | ```javascript 76 | db.collection.find().limit(10).skip(5) 77 | ``` 78 | 79 | These are basic examples, and MongoDB provides a wide range of operators and features to handle complex queries. Ensure that your queries align with your indexing strategy to achieve optimal performance. Regularly analyze and optimize your queries and indexes based on your application's workload. 80 | -------------------------------------------------------------------------------- /Example 01.py: -------------------------------------------------------------------------------- 1 | from pymongo import MongoClient 2 | 3 | # Connect to the MongoDB server running on localhost 4 | client = MongoClient('localhost', 27017) 5 | 6 | # Access a specific database 7 | db = client['my_database'] 8 | 9 | # Access a specific collection within the database 10 | users_collection = db['users'] 11 | 12 | # Insert a new document into the collection 13 | user = { 14 | 'name': 'Pankaj Sharma', 15 | 'age': 35, 16 | 'email': 'pankaj@codeswithpankaj.com' 17 | } 18 | result = users_collection.insert_one(user) 19 | print("User inserted successfully:", result.inserted_id) 20 | 21 | # Find all users in the collection 22 | all_users = users_collection.find() 23 | print("All users:") 24 | for user in all_users: 25 | print(user) 26 | 27 | # Close the connection to the MongoDB server 28 | client.close() -------------------------------------------------------------------------------- /Example 02.py: -------------------------------------------------------------------------------- 1 | from pymongo import MongoClient 2 | 3 | # Connect to the MongoDB server running on localhost 4 | client = MongoClient('localhost', 27017) 5 | 6 | # Access a specific database 7 | db = client['my_database'] 8 | 9 | # Access a specific collection within the database 10 | users_collection = db['users'] 11 | 12 | # Insert a new document into the collection 13 | user = { 14 | 'name': 'Riya Singh', 15 | 'age': 25, 16 | 'email': 'riya@p4n.in' 17 | } 18 | result = users_collection.insert_one(user) 19 | print("User inserted successfully:", result.inserted_id) 20 | 21 | # Find all users in the collection 22 | all_users = users_collection.find() 23 | print("All users:") 24 | for user in all_users: 25 | print(user) 26 | 27 | # Close the connection to the MongoDB server 28 | client.close() -------------------------------------------------------------------------------- /Example 03.py: -------------------------------------------------------------------------------- 1 | from pymongo import MongoClient 2 | 3 | # Connect to the MongoDB server running on localhost 4 | client = MongoClient('localhost', 27017) 5 | 6 | # Access a specific database 7 | db = client['my_database'] 8 | 9 | # Access a specific collection within the database 10 | users_collection = db['users'] 11 | 12 | # Define a list of users 13 | users = [ 14 | { 15 | 'name': 'Rahul Sharma', 16 | 'age': 28, 17 | 'email': 'rahul@p4n.in' 18 | }, 19 | { 20 | 'name': 'Neha Patel', 21 | 'age': 30, 22 | 'email': 'neha@p4n.in' 23 | }, 24 | { 25 | 'name': 'Amit Singh', 26 | 'age': 35, 27 | 'email': 'amit@p4n.in' 28 | } 29 | ] 30 | 31 | # Insert multiple users into the collection 32 | result = users_collection.insert_many(users) 33 | print("Users inserted successfully:", result.inserted_ids) 34 | 35 | # Find all users in the collection 36 | all_users = users_collection.find() 37 | print("All users:") 38 | for user in all_users: 39 | print(user) 40 | 41 | # Close the connection to the MongoDB server 42 | client.close() -------------------------------------------------------------------------------- /Example 04.py: -------------------------------------------------------------------------------- 1 | from pymongo import MongoClient 2 | import pandas as pd 3 | import random 4 | 5 | # Connect to the MongoDB server running on localhost 6 | client = MongoClient('localhost', 27017) 7 | 8 | # Create a new database 9 | db = client['sales_database'] 10 | 11 | # Access the collection 12 | sales_collection = db['sales'] 13 | 14 | # Define a function to generate random sales data and add it to the collection 15 | def generate_sales_data(num_transactions): 16 | sales_data = [] 17 | products = ['Product A', 'Product B', 'Product C'] 18 | for _ in range(num_transactions): 19 | transaction = { 20 | 'date': '2024-03-21', # Assuming all transactions happen on the same date for simplicity 21 | 'product': random.choice(products), 22 | 'quantity': random.randint(1, 10), 23 | 'total_amount': round(random.uniform(10.0, 100.0), 2) 24 | } 25 | sales_data.append(transaction) 26 | # Insert sales data into the collection 27 | sales_collection.insert_many(sales_data) 28 | print("Sales data added successfully.") 29 | 30 | # Define a function to analyze sales data 31 | def analyze_sales(): 32 | # Retrieve sales data from the collection 33 | sales_data = list(sales_collection.find()) 34 | 35 | # Convert sales data to a DataFrame for analysis 36 | df = pd.DataFrame(sales_data) 37 | 38 | # Perform data analysis 39 | total_sales = df['total_amount'].sum() 40 | average_quantity = df['quantity'].mean() 41 | most_sold_product = df['product'].value_counts().idxmax() 42 | 43 | # Print analysis results 44 | print("Total sales amount:", total_sales) 45 | print("Average quantity sold per transaction:", average_quantity) 46 | print("Most sold product:", most_sold_product) 47 | 48 | # Generate and add sales data to the collection 49 | generate_sales_data(100) 50 | 51 | # Analyze the sales data 52 | analyze_sales() 53 | 54 | # Close the connection to the MongoDB server 55 | client.close() -------------------------------------------------------------------------------- /Example_allinone.js: -------------------------------------------------------------------------------- 1 | show dbs; 2 | use school; 3 | 4 | db.createCollection("student"); 5 | show collections; 6 | 7 | db.student.insertOne({ name: "joy", age: 30, email: "joy@cwpc.in" }); 8 | //db.student.find(); 9 | 10 | db.student.insertMany([ 11 | { name: "John", age: 25, email: "john@example.com" }, 12 | { name: "Jane", age: 28, email: "jane@example.com" } 13 | ]); 14 | 15 | //db.student.find(); 16 | db.createCollection("products"); 17 | db.products.insertMany([ 18 | { name: "Laptop", price: 800, category: "Electronics", stock: 10 }, 19 | { name: "Phone", price: 600, category: "Electronics", stock: 25 }, 20 | { name: "Chair", price: 100, category: "Furniture", stock: 50 } 21 | ]); 22 | 23 | //db.products.find() 24 | 25 | db.products.updateOne( 26 | { name: "Laptop" }, // Filter 27 | { $inc: { stock: 5 } } // Update operation 28 | ); 29 | //db.products.find(); 30 | db.products.updateMany( 31 | { price: { $gt: 500 } }, // Filter 32 | { $set: { category: "Premium Electronics" } } // Update operation 33 | ); 34 | 35 | db.products.find({ price: { $gt: 700 } }); 36 | 37 | 38 | db.createCollection("st"); 39 | let students = []; 40 | 41 | for (let i = 1; i <= 100; i++) { 42 | students.push({ 43 | student_id: i, 44 | name: `Student ${i}`, 45 | age: Math.floor(Math.random() * 10) + 15, // age between 15 and 24 46 | grade: ["A", "B", "C", "D", "F"][Math.floor(Math.random() * 5)], 47 | subjects: ["Math", "Science", "English", "History", "Art"].slice(0, Math.floor(Math.random() * 5) + 1), 48 | enrollmentDate: new Date(2023, Math.floor(Math.random() * 12), Math.floor(Math.random() * 28) + 1) 49 | }); 50 | } 51 | db.st.insertMany(students); 52 | 53 | db.st.find(); 54 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2023 Pankaj Chouhan 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Understanding MongoDB: A Comprehensive Guide 2 | 3 | MongoDB is a leading NoSQL database known for its flexibility, scalability, and ease of use. In this comprehensive guide, we will explore MongoDB in depth, covering everything from installation to advanced features. Whether you're a developer, database administrator, or just curious about databases, this blog will provide you with a solid understanding of MongoDB. 4 | 5 | ## What is MongoDB? 6 | 7 | MongoDB is a free, open-source, cross-platform NoSQL database. Unlike traditional relational databases, it stores data in collections of documents. These documents are in a flexible and semi-structured BSON (Binary JSON) format. MongoDB is developed by MongoDB, Inc. and is written in C++. 8 | 9 | ### Key Features of MongoDB 10 | 11 | **1. Flexible Schema**: MongoDB doesn't require a predefined schema. You can store documents with different structures in the same collection, making it ideal for evolving data requirements. 12 | 13 | **2. Scalability**: MongoDB is designed for horizontal scalability. You can distribute your data across multiple servers to handle large workloads and growing data. 14 | 15 | **3. High Performance**: MongoDB can handle high write loads efficiently. It supports features like automatic sharding and load balancing to ensure optimal performance. 16 | 17 | **4. Rich Query Language**: MongoDB provides a powerful query language that supports various query operators, geospatial queries, and text search. 18 | 19 | **5. Aggregation Framework**: MongoDB's aggregation framework allows you to process and analyze data in sophisticated ways, such as grouping, filtering, and transforming data. 20 | 21 | ## Installation 22 | 23 | Before diving into MongoDB, you'll need to install it on your system. Here's a brief overview of how to do this: 24 | 25 | ### Windows 26 | 1. Download the Windows installer from the MongoDB website. 27 | 2. Follow the installation wizard, and MongoDB will be installed on your system. 28 | 29 | ### macOS 30 | 1. Install MongoDB using Homebrew with the command `brew tap mongodb/brew` and then `brew install mongodb-community`. 31 | 32 | ### Linux 33 | 1. Use your package manager (e.g., `apt` for Ubuntu) to install MongoDB with `sudo apt-get install mongodb`. 34 | 2. Alternatively, download the Linux tarball from the MongoDB website and follow the installation instructions. 35 | 36 | ## Basic Concepts 37 | 38 | ### Databases and Collections 39 | 40 | - **Database**: MongoDB organizes data into databases, similar to SQL databases. Each database can contain multiple collections. 41 | 42 | - **Collection**: Collections are groups of MongoDB documents. Think of them as the equivalent of SQL tables. 43 | 44 | ### Documents 45 | 46 | - **Document**: A document in MongoDB is a record in a collection, stored in BSON format. Documents can have different structures within the same collection. 47 | 48 | ### Fields 49 | 50 | - **Fields**: Fields are the individual key-value pairs within a document. 51 | 52 | ## CRUD Operations 53 | 54 | MongoDB supports CRUD operations, which are essential for interacting with the database: 55 | 56 | - **Create**: Insert documents into a collection. 57 | - **Read**: Query documents in a collection. 58 | - **Update**: Modify existing documents. 59 | - **Delete**: Remove documents from a collection. 60 | 61 | ## Data Modeling 62 | 63 | Data modeling in MongoDB is about designing your database schema to fit your application's needs. This includes structuring documents, defining relationships, and optimizing for query performance. 64 | 65 | ## Indexing 66 | 67 | Indexes in MongoDB improve query performance. By creating indexes on specific fields, you can make queries faster and more efficient. 68 | 69 | ## Aggregation 70 | 71 | MongoDB offers a robust aggregation framework for performing data transformations and analysis within the database. You can perform operations like grouping, filtering, and calculating aggregates. 72 | 73 | ## Security 74 | 75 | Securing your MongoDB installation is crucial. MongoDB provides authentication, authorization, and other security features to protect your data from unauthorized access. 76 | 77 | ## Scaling 78 | 79 | MongoDB supports horizontal scaling through sharding. This allows you to distribute your data across multiple servers to handle large datasets and high traffic loads, ensuring seamless scalability. 80 | --------------------------------------------------------------------------------