From 5fedd10aff469f6a23aeaf3f406116b8e03865f7 Mon Sep 17 00:00:00 2001 From: Vipul_Lakum Date: Sun, 9 Jun 2024 15:39:38 +0530 Subject: [PATCH] mongoDB-basics added --- docs/MongoDB/_category.json | 8 ++ docs/MongoDB/create-database.md | 83 ++++++++++++++ docs/MongoDB/data-modeling.md | 168 ++++++++++++++++++++++++++++ docs/MongoDB/drop-database.md | 75 +++++++++++++ docs/MongoDB/home.md | 20 ++++ docs/MongoDB/mongodb-advantages.md | 65 +++++++++++ docs/MongoDB/mongodb-environment.md | 152 +++++++++++++++++++++++++ docs/MongoDB/overview.md | 63 +++++++++++ 8 files changed, 634 insertions(+) create mode 100644 docs/MongoDB/_category.json create mode 100644 docs/MongoDB/create-database.md create mode 100644 docs/MongoDB/data-modeling.md create mode 100644 docs/MongoDB/drop-database.md create mode 100644 docs/MongoDB/home.md create mode 100644 docs/MongoDB/mongodb-advantages.md create mode 100644 docs/MongoDB/mongodb-environment.md create mode 100644 docs/MongoDB/overview.md diff --git a/docs/MongoDB/_category.json b/docs/MongoDB/_category.json new file mode 100644 index 000000000..92933d9d9 --- /dev/null +++ b/docs/MongoDB/_category.json @@ -0,0 +1,8 @@ +{ + "label": "MongoDB", + "position": 12, + "link": { + "type": "generated-index", + "description": "MongoDB is a popular NoSQL database known for its high performance, high availability, and easy scalability. It uses a flexible, JSON-like data model, which allows for the storage of complex data structures. MongoDB is designed to handle a wide variety of data types and workloads, making it a versatile choice for modern applications. Key features include document-oriented storage, powerful query capabilities, indexing, replication, and sharding. MongoDB is widely used in various industries for applications requiring fast development cycles, large-scale data processing, and real-time analytics." + } +} \ No newline at end of file diff --git a/docs/MongoDB/create-database.md b/docs/MongoDB/create-database.md new file mode 100644 index 000000000..a5bc228db --- /dev/null +++ b/docs/MongoDB/create-database.md @@ -0,0 +1,83 @@ +--- +id: mongodb-create-database +title: MongoDB - Create Database +sidebar_label: Create Database +sidebar_position: 6 +tags: [mongodb, create database, commands] +description: Learn how to create a database in MongoDB using the use command, along with examples and additional commands. +--- + +# MongoDB - Create Database + +In this chapter, we will see how to create a database in MongoDB. + +## The `use` Command + +The `use DATABASE_NAME` command in MongoDB is used to create a database. The command will create a new database if it doesn't exist; otherwise, it will return the existing database. + +### Syntax + +The basic syntax of the `use DATABASE` statement is as follows: + +```sql +use DATABASE_NAME +``` + +### Example + +If you want to use a database named `mydb`, the `use DATABASE` statement would be as follows: + +```bash +> use mydb +switched to db mydb +``` + +To check your currently selected database, use the command `db`: + +```bash +> db +mydb +``` + +If you want to check your databases list, use the command `show dbs`: + +```bash +> show dbs +local 0.78125GB +test 0.23012GB +``` + +Your created database (`mydb`) is not present in the list. To display the database, you need to insert at least one document into it: + +```bash +> db.movie.insert({"name":"tutorials point"}) +> show dbs +local 0.78125GB +mydb 0.23012GB +test 0.23012GB +``` + +In MongoDB, the default database is `test`. If you didn't create any database, then collections will be stored in the `test` database. + +## Data Modeling Diagram + +```mermaid +graph TD + A[Create Database] --> B[use Command] + B --> C[Syntax] + B --> D[Example] + D --> E[Switch Database] + D --> F[Check Current Database] + D --> G[Check Databases List] + D --> H[Insert Document] + D --> I[Display Database] +``` + +## Command Summary + +| Command | Description | +|-----------------------------------|--------------------------------------------------------------| +| `use DATABASE_NAME` | Create or switch to a database | +| `db` | Check the currently selected database | +| `show dbs` | List all databases | +| `db..insert(document)`| Insert a document into a collection | diff --git a/docs/MongoDB/data-modeling.md b/docs/MongoDB/data-modeling.md new file mode 100644 index 000000000..3e12fd305 --- /dev/null +++ b/docs/MongoDB/data-modeling.md @@ -0,0 +1,168 @@ +--- +id: mongodb-data-modeling +title: MongoDB - Data Modelling +sidebar_label: Data Modelling +sidebar_position: 5 +tags: [mongodb, data modeling, schema design] +description: Learn about data modeling in MongoDB, including embedded and normalized data models, with examples and considerations for schema design. +--- + +# MongoDB - Data Modelling + +Data in MongoDB has a flexible schema. Documents in the same collection do not need to have the same set of fields or structure. Common fields in a collection’s documents may hold different types of data. + +## Data Model Design + +MongoDB provides two types of data models: Embedded data model and Normalized data model. Based on the requirement, you can use either of the models while preparing your document. + +### Embedded Data Model + +In this model, you can have (embed) all the related data in a single document. It is also known as the de-normalized data model. + +For example, assume we are getting the details of employees in three different documents, namely, Personal_details, Contact, and Address. You can embed all three documents into a single one as shown below: + +```json +{ + "_id": "ObjectId", + "Emp_ID": "10025AE336", + "Personal_details": { + "First_Name": "Radhika", + "Last_Name": "Sharma", + "Date_Of_Birth": "1995-09-26" + }, + "Contact": { + "email": "radhika_sharma.123@gmail.com", + "phone": "9848022338" + }, + "Address": { + "city": "Hyderabad", + "Area": "Madapur", + "State": "Telangana" + } +} +``` + +### Normalized Data Model + +In this model, you can refer to the sub-documents in the original document using references. For example, you can rewrite the above document in the normalized model as: + +#### Employee + +```json +{ + "_id": "", + "Emp_ID": "10025AE336" +} +``` + +#### Personal_details + +```json +{ + "_id": "", + "empDocID": "", + "First_Name": "Radhika", + "Last_Name": "Sharma", + "Date_Of_Birth": "1995-09-26" +} +``` + +#### Contact + +```json +{ + "_id": "", + "empDocID": "", + "email": "radhika_sharma.123@gmail.com", + "phone": "9848022338" +} +``` + +#### Address + +```json +{ + "_id": "", + "empDocID": "", + "city": "Hyderabad", + "Area": "Madapur", + "State": "Telangana" +} +``` + +## Considerations while Designing Schema in MongoDB + +1. **Design your schema according to user requirements.** +2. **Combine objects into one document if you will use them together. Otherwise, separate them (but make sure there is no need for joins).** +3. **Duplicate the data (but limited) because disk space is cheap compared to compute time.** +4. **Do joins while writing, not on reading.** +5. **Optimize your schema for the most frequent use cases.** +6. **Do complex aggregation in the schema.** + +## Example + +Suppose a client needs a database design for their blog/website. Let's see the differences between RDBMS and MongoDB schema design. The website has the following requirements: + +- Every post has a unique title, description, and URL. +- Every post can have one or more tags. +- Every post has the name of its publisher and the total number of likes. +- Every post has comments given by users along with their name, message, date-time, and likes. +- On each post, there can be zero or more comments. + +### RDBMS Schema Design + +In RDBMS schema design, for the above requirements, you will have at least three tables. + +### MongoDB Schema Design + +In MongoDB schema design, you will have one collection called `post` with the following structure: + +```json +{ + "_id": "POST_ID", + "title": "TITLE_OF_POST", + "description": "POST_DESCRIPTION", + "by": "POST_BY", + "url": "URL_OF_POST", + "tags": ["TAG1", "TAG2", "TAG3"], + "likes": "TOTAL_LIKES", + "comments": [ + { + "user": "COMMENT_BY", + "message": "TEXT", + "dateCreated": "DATE_TIME", + "like": "LIKES" + }, + { + "user": "COMMENT_BY", + "message": "TEXT", + "dateCreated": "DATE_TIME", + "like": "LIKES" + } + ] +} +``` + +So, while showing the data, in RDBMS you need to join three tables, but in MongoDB, data will be shown from one collection only. + +### Data Modeling Diagram + +```mermaid +graph TD + A[Data Model Design] --> B[Embedded Data Model] + A --> C[Normalized Data Model] + B --> D[Single Document] + C --> E[Separate Documents] + E --> F[References] +``` + +### Data Modeling Summary + +| Feature | Embedded Data Model | Normalized Data Model | +|---------------------------------|-----------------------------|-----------------------------| +| **Data Storage** | Single document | Separate documents | +| **Schema Complexity** | Simple | Complex | +| **Performance** | Fast reads | Fast writes | +| **Use Case** | High read/write frequency | Large data with references | + +MongoDB provides a flexible and efficient way to model your data based on your application needs. Choosing the right data model depends on the use case and access patterns. diff --git a/docs/MongoDB/drop-database.md b/docs/MongoDB/drop-database.md new file mode 100644 index 000000000..262a1ebd5 --- /dev/null +++ b/docs/MongoDB/drop-database.md @@ -0,0 +1,75 @@ +--- +id: mongodb-drop-database +title: MongoDB - Drop Database +sidebar_label: Drop Database +sidebar_position: 7 +tags: [mongodb, drop database, commands] +description: Learn how to drop a database in MongoDB using the dropDatabase() command, along with examples and additional commands. +--- + +# MongoDB - Drop Database + +In this chapter, we will see how to drop a database using the MongoDB command. + +## The `dropDatabase()` Method + +The MongoDB `db.dropDatabase()` command is used to drop an existing database. + +### Syntax + +The basic syntax of the `dropDatabase()` command is as follows: + +```sql +db.dropDatabase() +``` + +This will delete the selected database. If you have not selected any database, then it will delete the default `test` database. + +### Example + +First, check the list of available databases by using the command `show dbs`: + +```bash +> show dbs +local 0.78125GB +mydb 0.23012GB +test 0.23012GB +``` + +If you want to delete the new database `mydb`, the `dropDatabase()` command would be as follows: + +```bash +> use mydb +switched to db mydb +> db.dropDatabase() +{ "dropped" : "mydb", "ok" : 1 } +``` + +Now check the list of databases: + +```bash +> show dbs +local 0.78125GB +test 0.23012GB +``` + +## Dropping Database Diagram + +```mermaid +graph TD + A[Drop Database] --> B[dropDatabase Method] + B --> C[Syntax] + B --> D[Example] + D --> E[Check Available Databases] + D --> F[Switch to Database] + D --> G[Drop Database] + D --> H[Verify Database Removal] +``` + +## Command Summary + +| Command | Description | +|-------------------------|-------------------------------------------------------| +| `db.dropDatabase()` | Drop the currently selected database | +| `show dbs` | List all databases | +| `use DATABASE_NAME` | Switch to a specific database | diff --git a/docs/MongoDB/home.md b/docs/MongoDB/home.md new file mode 100644 index 000000000..526834232 --- /dev/null +++ b/docs/MongoDB/home.md @@ -0,0 +1,20 @@ +--- +id: mongodb-home +title: MongoDB Tutorial Home +sidebar_label: Home +sidebar_position: 1 +tags: [mongodb, nosql, database] +description: In this tutorial, you will learn about MongoDB, its concepts, architecture, and applications, enabling you to create and deploy highly scalable and performance-oriented databases. +--- + +# MongoDB Tutorial + +MongoDB is an open-source document database and leading NoSQL database. MongoDB is written in C++. This tutorial will give you great understanding on MongoDB concepts needed to create and deploy a highly scalable and performance-oriented database. + +### Audience + +This tutorial is designed for Software Professionals who are willing to learn MongoDB Database in simple and easy steps. It will throw light on MongoDB concepts and after completing this tutorial you will be at an intermediate level of expertise, from where you can take yourself at higher level of expertise. + +### Prerequisites + +Before proceeding with this tutorial, you should have a basic understanding of database, text editor and execution of programs, etc. Because we are going to develop high performance database, so it will be good if you have an understanding on the basic concepts of Database (RDBMS). diff --git a/docs/MongoDB/mongodb-advantages.md b/docs/MongoDB/mongodb-advantages.md new file mode 100644 index 000000000..398db130d --- /dev/null +++ b/docs/MongoDB/mongodb-advantages.md @@ -0,0 +1,65 @@ +--- +id: mongodb-advantages +title: MongoDB - Advantages +sidebar_label: Advantages +sidebar_position: 3 +tags: [mongodb, advantages, nosql, database] +description: In this section, you will learn about the various advantages of using MongoDB over traditional relational database management systems (RDBMS). +--- + +# MongoDB - Advantages + +Any relational database has a typical schema design that shows the number of tables and the relationship between these tables. While in MongoDB, there is no concept of relationship. + +## Advantages of MongoDB over RDBMS + +- **Schema-less:** MongoDB is a document database in which one collection holds different documents. The number of fields, content, and size of the document can differ from one document to another. +- **Structure of a single object is clear.** +- **No complex joins.** +- **Deep query-ability:** MongoDB supports dynamic queries on documents using a document-based query language that's nearly as powerful as SQL. +- **Tuning.** +- **Ease of scale-out:** MongoDB is easy to scale. +- **Conversion/mapping of application objects to database objects not needed.** +- **Uses internal memory for storing the (windowed) working set, enabling faster access of data.** + +> **Note:** MongoDB's schema-less design and flexible structure make it an excellent choice for applications that require rapid development and iterative changes. + +## Why Use MongoDB? + +- **Document Oriented Storage:** Data is stored in the form of JSON style documents. +- **Index on any attribute.** +- **Replication and high availability.** +- **Auto-Sharding.** +- **Rich queries.** +- **Fast in-place updates.** +- **Professional support by MongoDB.** + +## Where to Use MongoDB? + +- **Big Data.** +- **Content Management and Delivery.** +- **Mobile and Social Infrastructure.** +- **User Data Management.** +- **Data Hub.** + +### MongoDB Architecture Diagram + +```mermaid +graph TD + A[Client] -->|Read/Write| B[MongoDB Server] + B -->|Stores data| C[Database] + C -->|Contains| D[Collection] + D -->|Holds| E[Document] +``` + +### Advantages Summary + +| Feature | Description | +|---------|-------------| +| Schema-less | Flexible document structure, no predefined schema required. | +| No complex joins | Simplifies queries by avoiding complex joins. | +| Deep query-ability | Powerful querying capabilities using a document-based query language. | +| Easy scale-out | Simplified scaling process. | +| Fast access | Uses internal memory for fast data access. | + +MongoDB offers numerous advantages over traditional RDBMS, particularly for applications that require flexibility, scalability, and performance. Its document-oriented storage model and rich querying capabilities make it a versatile choice for modern data-driven applications. diff --git a/docs/MongoDB/mongodb-environment.md b/docs/MongoDB/mongodb-environment.md new file mode 100644 index 000000000..92b0be04e --- /dev/null +++ b/docs/MongoDB/mongodb-environment.md @@ -0,0 +1,152 @@ +--- +id: mongodb-environment +title: MongoDB - Environment +sidebar_label: Environment +sidebar_position: 4 +tags: [mongodb, environment, setup, installation] +description: Learn how to set up and configure MongoDB on Windows and Ubuntu environments, including installation steps and commands. +--- + +# MongoDB - Environment + +Let us now see how to install MongoDB on Windows and Ubuntu. + +## Install MongoDB On Windows + +To install MongoDB on Windows, first download the latest release of MongoDB from [MongoDB Download Center](https://www.mongodb.com/download-center). + +### MongoDB Cloud +Enter the required details, select the Server tab, in it you can choose the version of MongoDB, operating system, and packaging as: + +### MongoDB Community +Now install the downloaded file. By default, it will be installed in the folder `C:\Program Files\`. + +MongoDB requires a data folder to store its files. The default location for the MongoDB data directory is `c:\data\db`. So you need to create this folder using the Command Prompt. Execute the following command sequence: + +```sh +C:\>md data +C:\>md data\db +``` + +Then you need to set the `dbpath` to the created directory in `mongod.exe`. For the same, issue the following commands: + +In the command prompt, navigate to the bin directory current in the MongoDB installation folder. Suppose my installation folder is `C:\Program Files\MongoDB`. + +```sh +C:\Users\XYZ>d: +C:\>cd "C:\Program Files\MongoDB\Server\4.2\bin" +C:\Program Files\MongoDB\Server\4.2\bin>mongod.exe --dbpath "C:\data" +``` + +This will show "waiting for connections" message on the console output, indicating that the `mongod.exe` process is running successfully. + +Now, to run MongoDB, open another command prompt and issue the following command: + +```sh +C:\Program Files\MongoDB\Server\4.2\bin>mongo.exe +``` + +```plaintext +MongoDB shell version v4.2.1 +connecting to: mongodb://127.0.0.1:27017/?compressors=disabled&gssapiServiceName=mongodb +Implicit session: session { "id" : UUID("4260beda-f662-4cbe-9bc7-5c1f2242663c") } +MongoDB server version: 4.2.1 +> +``` + +This shows that MongoDB is installed and running successfully. Next time when you run MongoDB, you need to issue only these commands: + +```sh +C:\Program Files\MongoDB\Server\4.2\bin>mongod.exe --dbpath "C:\data" +C:\Program Files\MongoDB\Server\4.2\bin>mongo.exe +``` + +## Install MongoDB on Ubuntu + +Run the following command to import the MongoDB public GPG key: + +```sh +sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 7F0CEB10 +``` + +Create a `/etc/apt/sources.list.d/mongodb.list` file using the following command: + +```sh +echo 'deb http://downloads-distro.mongodb.org/repo/ubuntu-upstart dist 10gen' | sudo tee /etc/apt/sources.list.d/mongodb.list +``` + +Now issue the following command to update the repository: + +```sh +sudo apt-get update +``` + +Next, install MongoDB by using the following command: + +```sh +sudo apt-get install -y mongodb-org +``` + +Now MongoDB is installed successfully. + +### Start MongoDB + +```sh +sudo service mongod start +``` + +### Stop MongoDB + +```sh +sudo service mongod stop +``` + +### Restart MongoDB + +```sh +sudo service mongod restart +``` + +To use MongoDB, run the following command: + +```sh +mongo +``` + +This will connect you to the running MongoDB instance. + +## MongoDB Help + +To get a list of commands, type `db.help()` in MongoDB client. This will give you a list of commands as shown in the following screenshot. + +## MongoDB Statistics + +To get stats about the MongoDB server, type the command `db.stats()` in MongoDB client. This will show the database name, number of collections, and documents in the database. + +### MongoDB Installation Process Diagram + +```mermaid +graph TD + A[Download MongoDB] --> B[Install MongoDB] + B --> C[Create Data Directory] + C --> D[Run mongod] + D --> E[Run mongo] + E --> F[MongoDB Shell] +``` + +### MongoDB Commands Summary + +| Command | Description | +|---------|-------------| +| `md data` | Create data directory | +| `mongod.exe --dbpath "C:\data"` | Start MongoDB server | +| `mongo.exe` | Connect to MongoDB server | +| `sudo apt-get update` | Update package list | +| `sudo apt-get install -y mongodb-org` | Install MongoDB on Ubuntu | +| `sudo service mongod start` | Start MongoDB service | +| `sudo service mongod stop` | Stop MongoDB service | +| `sudo service mongod restart` | Restart MongoDB service | +| `db.help()` | Get a list of commands in MongoDB client | +| `db.stats()` | Get statistics about MongoDB server | + +MongoDB provides a flexible and scalable environment for database management. The above steps guide you through installing and setting up MongoDB on Windows and Ubuntu environments. diff --git a/docs/MongoDB/overview.md b/docs/MongoDB/overview.md new file mode 100644 index 000000000..248a0ec52 --- /dev/null +++ b/docs/MongoDB/overview.md @@ -0,0 +1,63 @@ +--- +id: mongodb-overview +title: MongoDB - Overview +sidebar_label: Overview +sidebar_position: 2 +tags: [mongodb, overview, nosql, database] +description: In this section, you will get an overview of MongoDB, its components, and how it compares to traditional RDBMS systems. +--- + +# MongoDB - Overview + +MongoDB is a cross-platform, document-oriented database that provides high performance, high availability, and easy scalability. MongoDB works on the concept of collections and documents. + +## Database + +A database is a physical container for collections. Each database gets its own set of files on the file system. A single MongoDB server typically has multiple databases. + +## Collection + +A collection is a group of MongoDB documents. It is the equivalent of an RDBMS table. A collection exists within a single database. Collections do not enforce a schema. Documents within a collection can have different fields. Typically, all documents in a collection are of similar or related purpose. + +## Document + +A document is a set of key-value pairs. Documents have dynamic schema. Dynamic schema means that documents in the same collection do not need to have the same set of fields or structure, and common fields in a collection's documents may hold different types of data. + +> **Note:** MongoDB documents have a flexible schema, which allows you to store different types of data within the same collection without needing to predefine a rigid structure. + +## Comparison with RDBMS + +The following table shows the relationship of RDBMS terminology with MongoDB: + +| RDBMS | MongoDB | +|-------------|--------------| +| Database | Database | +| Table | Collection | +| Tuple/Row | Document | +| Column | Field | +| Table Join | Embedded Documents | +| Primary Key | Primary Key (Default key `_id` provided by MongoDB itself) | +| mysqld/Oracle | `mongod` | +| mysql/sqlplus | `mongo` | + +## MongoDB Architecture + +```mermaid +graph TD + A[Client] -->|Read/Write| B[MongoDB Server] + B -->|Stores data| C[Database] + C -->|Contains| D[Collection] + D -->|Holds| E[Document] +``` + +### MongoDB Components + +- **Client:** The MongoDB client, which sends queries to the server. +- **Server (mongod):** The MongoDB server, which processes requests from clients. +- **Database:** A physical container for collections. +- **Collection:** A grouping of MongoDB documents. +- **Document:** A set of key-value pairs. + +## Summary + +MongoDB is a flexible, scalable database solution that uses a document-oriented model, making it different from traditional relational databases. It supports dynamic schema, making it easy to store and retrieve various types of data within a single collection.