diff --git a/docs/MongoDB/mongodb-create-backup.md b/docs/MongoDB/mongodb-create-backup.md new file mode 100644 index 000000000..0d8759b7f --- /dev/null +++ b/docs/MongoDB/mongodb-create-backup.md @@ -0,0 +1,88 @@ +--- +id: mongodb-create-backup +title: MongoDB - Create Backup +sidebar_label: Create Backup +sidebar_position: 22 +tags: [mongodb, backup, database, mongodump, mongorestore] +description: Learn how to create and restore backups in MongoDB using the mongodump and mongorestore commands. +--- + +# MongoDB - Create Backup + +In this chapter, we will see how to create a backup in MongoDB. + +## Dump MongoDB Data + +To create a backup of a database in MongoDB, use the `mongodump` command. This command dumps the entire data of your server into the dump directory. There are many options available to limit the amount of data or create a backup of your remote server. + +### Syntax + +The basic syntax of the `mongodump` command is as follows: + +``` +mongodump +``` + +### Example + +Start your `mongod` server. Assuming that your `mongod` server is running on `localhost` and port `27017`, open a command prompt, go to the `bin` directory of your MongoDB instance, and type the command `mongodump`. + +Consider the `mycol` collection has the following data. + +``` +mongodump +``` + +The command will connect to the server running at `127.0.0.1` and port `27017` and back up all data of the server to the directory `/bin/dump/`. Following is the output of the command: + +```plaintext +2023-06-10T12:34:56.789+0000 writing mydb.mycol to /bin/dump/mydb/mycol.bson +2023-06-10T12:34:56.789+0000 done +``` + +## Available Options for `mongodump` + +| Syntax | Description | Example | +|---------------------------------------------|----------------------------------------------------------|---------------------------------------------------------| +| `mongodump --host HOST_NAME --port PORT_NUMBER` | This command will back up all databases of the specified `mongod` instance. | `mongodump --host tutorialspoint.com --port 27017` | +| `mongodump --dbpath DB_PATH --out BACKUP_DIRECTORY` | This command will back up only the specified database at the specified path. | `mongodump --dbpath /data/db/ --out /data/backup/` | +| `mongodump --collection COLLECTION --db DB_NAME` | This command will back up only the specified collection of the specified database. | `mongodump --collection mycol --db test` | + +## Restore Data + +To restore backup data, use MongoDB's `mongorestore` command. This command restores all of the data from the backup directory. + +### Syntax + +The basic syntax of the `mongorestore` command is: + +``` +mongorestore +``` + +### Example + +Following is the output of the command: + +```plaintext +2023-06-10T12:34:56.789+0000 preparing to restore mydb.mycol from /bin/dump/mydb/mycol.bson +2023-06-10T12:34:56.789+0000 done +``` + +### Diagram + +```mermaid +graph TD; + A[Client Application] --> B[Mongod Server] + B --> C{mongodump} + C --> D[Backup Directory] + E[Backup Directory] --> F{mongorestore} + F --> B +``` + +:::note +- Ensure the `mongod` server is running before executing the `mongodump` or `mongorestore` commands. +- Use appropriate options with `mongodump` to back up specific databases or collections. +- The backup directory should be accessible and writable by the MongoDB instance. +::: +Creating backups regularly ensures that you have a recovery option in case of data loss or corruption. \ No newline at end of file diff --git a/docs/MongoDB/mongodb-deployment.md b/docs/MongoDB/mongodb-deployment.md new file mode 100644 index 000000000..cb62aaf51 --- /dev/null +++ b/docs/MongoDB/mongodb-deployment.md @@ -0,0 +1,89 @@ +--- +id: mongodb-deployment +title: MongoDB - Deployment +sidebar_label: Deployment +sidebar_position: 23 +tags: [mongodb, deployment, monitoring, mongostat, mongotop] +description: Learn how to deploy and monitor MongoDB in a production environment. +--- + +# MongoDB - Deployment + +When you are preparing a MongoDB deployment, you should try to understand how your application is going to hold up in production. It’s a good idea to develop a consistent, repeatable approach to managing your deployment environment so that you can minimize any surprises once you’re in production. + +The best approach incorporates prototyping your setup, conducting load testing, monitoring key metrics, and using that information to scale your setup. The key part of the approach is to proactively monitor your entire system - this will help you understand how your production system will hold up before deploying and determine where you will need to add capacity. Having insight into potential spikes in your memory usage, for example, could help put out a write-lock fire before it starts. + +## Monitoring Your Deployment + +To monitor your deployment, MongoDB provides some of the following commands: + +### `mongostat` + +This command checks the status of all running `mongod` instances and returns counters of database operations. These counters include inserts, queries, updates, deletes, and cursors. The command also shows when you’re hitting page faults and showcases your lock percentage. This means that you're running low on memory, hitting write capacity, or have some performance issues. + +To run the command, start your `mongod` instance. In another command prompt, go to the `bin` directory of your MongoDB installation and type `mongostat`. + +```shell +D:\set up\mongodb\bin>mongostat +``` + +Following is the output of the command: + +```plaintext +insert query update delete getmore command % dirty % used flushes vsize res qrw arw net_in net_out conn time + *0 *0 *0 *0 0 1|0 0 0 0 54.3M 2.0M 0|0 0|0 0 0 1 2024-06-10T12:34:56.789+0000 +``` + +### `mongotop` + +This command tracks and reports the read and write activity of MongoDB instances on a collection basis. By default, `mongotop` returns information each second, which you can change accordingly. You should check that this read and write activity matches your application intention, and you’re not firing too many writes to the database at a time, reading too frequently from a disk, or exceeding your working set size. + +To run the command, start your `mongod` instance. In another command prompt, go to the `bin` directory of your MongoDB installation and type `mongotop`. + +```shell +D:\set up\mongodb\bin>mongotop +``` + +Following is the output of the command: + +```plaintext +ns total read write 2024-06-10T12:34:56.789+0000 +mydb.mycol 0ms 0ms 0ms +``` + +To change the `mongotop` command to return information less frequently, specify a specific number after the `mongotop` command. + +```shell +D:\set up\mongodb\bin>mongotop 30 +``` + +The above example will return values every 30 seconds. + +## MongoDB Management Service (MMS) + +Apart from the MongoDB tools, 10gen provides a free, hosted monitoring service, MongoDB Management Service (MMS), that provides a dashboard and gives you a view of the metrics from your entire cluster. + +## Diagram + +```mermaid +graph TD; + A[Prepare Deployment] --> B[Prototype Setup] + B --> C[Load Testing] + C --> D[Monitor Key Metrics] + D --> E[Scale Setup] + E --> F[Deploy in Production] + F --> G[Monitor Deployment] + G --> H{Monitoring Tools} + H --> I[mongostat] + H --> J[mongotop] + H --> K[MMS] +``` + +:::note + +- Regularly prototype, test, and monitor your deployment environment. +- Use `mongostat` to check the status of your `mongod` instances and monitor database operations. +- Use `mongotop` to track and report read/write activity on a collection basis. +- Utilize MongoDB Management Service (MMS) for comprehensive monitoring and a visual dashboard. +::: +Having a well-planned and monitored deployment strategy ensures the stability and performance of your MongoDB in a production environment. diff --git a/docs/MongoDB/mongodb-java-operations.md b/docs/MongoDB/mongodb-java-operations.md new file mode 100644 index 000000000..2dae88aee --- /dev/null +++ b/docs/MongoDB/mongodb-java-operations.md @@ -0,0 +1,457 @@ +--- +id: mongodb-java-operations +title: MongoDB - Java Operations +sidebar_label: Java Operations +sidebar_position: 24 +tags: [mongodb, java, database, crud, connection] +description: Learn how to perform CRUD operations with MongoDB using Java. +--- +# MongoDB - Java + +## Installation + +Before you start using MongoDB in your Java programs, ensure that you have MongoDB CLIENT and Java set up on your machine. You can refer to Java tutorials for Java installation on your machine. Now, let's check how to set up MongoDB CLIENT. + +1. **Download the necessary JAR files**: + - `mongodb-driver-3.11.2.jar` + - `mongodb-driver-core-3.11.2.jar` + + Make sure to download the latest release of these JAR files. + +2. **Include the JAR files in your classpath**. +:::note +You can download the JAR files from the [MongoDB Java Driver](https://mongodb.github.io/mongo-java-driver/) website. +::: +## Connect to Database + +To connect to a database, specify the database name. If the database doesn't exist, MongoDB creates it automatically. + +```java +import com.mongodb.client.MongoDatabase; +import com.mongodb.MongoClient; +import com.mongodb.MongoCredential; + +public class ConnectToDB { + public static void main( String args[] ) { + // Creating a Mongo client + MongoClient mongo = new MongoClient( "localhost" , 27017 ); + + // Creating Credentials + MongoCredential credential; + credential = MongoCredential.createCredential("sampleUser", "myDb", "password".toCharArray()); + System.out.println("Connected to the database successfully"); + + // Accessing the database + MongoDatabase database = mongo.getDatabase("myDb"); + System.out.println("Credentials ::"+ credential); + } +} +``` + +**Compile and Run**: + +```bash +$ javac ConnectToDB.java +$ java ConnectToDB +``` + +**Output**: + +``` +Connected to the database successfully +Credentials ::MongoCredential{mechanism = null, userName = 'sampleUser', source = 'myDb', password = , mechanismProperties = {}} +``` + +## Create a Collection + +To create a collection, use the `createCollection()` method of the `com.mongodb.client.MongoDatabase` class. + +```java +import com.mongodb.client.MongoDatabase; +import com.mongodb.MongoClient; +import com.mongodb.MongoCredential; + +public class CreatingCollection { + public static void main( String args[] ) { + // Creating a Mongo client + MongoClient mongo = new MongoClient( "localhost" , 27017 ); + + // Creating Credentials + MongoCredential credential; + credential = MongoCredential.createCredential("sampleUser", "myDb", "password".toCharArray()); + System.out.println("Connected to the database successfully"); + + // Accessing the database + MongoDatabase database = mongo.getDatabase("myDb"); + + // Creating a collection + database.createCollection("sampleCollection"); + System.out.println("Collection created successfully"); + } +} +``` + +**Compile and Run**: + +```bash +$ javac CreatingCollection.java +$ java CreatingCollection +``` + +**Output**: + +``` +Connected to the database successfully +Collection created successfully +``` + +## Getting/Selecting a Collection + +To get/select a collection from the database, use the `getCollection()` method of the `com.mongodb.client.MongoDatabase` class. + +```java +import com.mongodb.client.MongoCollection; +import com.mongodb.client.MongoDatabase; +import org.bson.Document; +import com.mongodb.MongoClient; +import com.mongodb.MongoCredential; + +public class SelectingCollection { + public static void main( String args[] ) { + // Creating a Mongo client + MongoClient mongo = new MongoClient( "localhost" , 27017 ); + + // Creating Credentials + MongoCredential credential; + credential = MongoCredential.createCredential("sampleUser", "myDb", "password".toCharArray()); + System.out.println("Connected to the database successfully"); + + // Accessing the database + MongoDatabase database = mongo.getDatabase("myDb"); + + // Retrieving a collection + MongoCollection collection = database.getCollection("sampleCollection"); + System.out.println("Collection myCollection selected successfully"); + } +} +``` + +**Compile and Run**: + +```bash +$ javac SelectingCollection.java +$ java SelectingCollection +``` + +**Output**: + +``` +Connected to the database successfully +Collection myCollection selected successfully +``` + +## Insert a Document + +To insert a document into MongoDB, use the `insertOne()` method of the `com.mongodb.client.MongoCollection` class. + +```java +import com.mongodb.client.MongoCollection; +import com.mongodb.client.MongoDatabase; +import org.bson.Document; +import com.mongodb.MongoClient; + +public class InsertingDocument { + public static void main( String args[] ) { + // Creating a Mongo client + MongoClient mongo = new MongoClient( "localhost" , 27017 ); + + // Accessing the database + MongoDatabase database = mongo.getDatabase("myDb"); + + // Creating a collection + database.createCollection("sampleCollection"); + System.out.println("Collection created successfully"); + + // Retrieving a collection + MongoCollection collection = database.getCollection("sampleCollection"); + System.out.println("Collection sampleCollection selected successfully"); + + // Creating a document + Document document = new Document("title", "MongoDB") + .append("description", "database") + .append("likes", 100) + .append("url", "http://www.tutorialspoint.com/mongodb/") + .append("by", "tutorials point"); + + // Inserting document into the collection + collection.insertOne(document); + System.out.println("Document inserted successfully"); + } +} +``` + +**Compile and Run**: + +```bash +$ javac InsertingDocument.java +$ java InsertingDocument +``` + +**Output**: + +``` +Connected to the database successfully +Collection sampleCollection selected successfully +Document inserted successfully +``` + +## Retrieve All Documents + +To select all documents from the collection, use the `find()` method of the `com.mongodb.client.MongoCollection` class. This method returns a cursor, so you need to iterate this cursor. + +```java +import com.mongodb.client.FindIterable; +import com.mongodb.client.MongoCollection; +import com.mongodb.client.MongoDatabase; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import org.bson.Document; +import com.mongodb.MongoClient; +import com.mongodb.MongoCredential; + +public class RetrievingAllDocuments { + public static void main( String args[] ) { + // Creating a Mongo client + MongoClient mongo = new MongoClient( "localhost" , 27017 ); + + // Creating Credentials + MongoCredential credential; + credential = MongoCredential.createCredential("sampleUser", "myDb", "password".toCharArray()); + System.out.println("Connected to the database successfully"); + + // Accessing the database + MongoDatabase database = mongo.getDatabase("myDb"); + + // Retrieving a collection + MongoCollection collection = database.getCollection("sampleCollection"); + System.out.println("Collection sampleCollection selected successfully"); + + // Creating documents + Document document1 = new Document("title", "MongoDB") + .append("description", "database") + .append("likes", 100) + .append("url", "http://www.tutorialspoint.com/mongodb/") + .append("by", "tutorials point"); + Document document2 = new Document("title", "RethinkDB") + .append("description", "database") + .append("likes", 200) + .append("url", "http://www.tutorialspoint.com/rethinkdb/") + .append("by", "tutorials point"); + + // Inserting documents into the collection + List list = new ArrayList(); + list.add(document1); + list.add(document2); + collection.insertMany(list); + + // Getting the iterable object + FindIterable iterDoc = collection.find(); + int i = 1; + + // Getting the iterator + Iterator it = iterDoc.iterator(); + while (it.hasNext()) { + System.out.println(it.next()); + i++; + } + } +} +``` + +**Compile and Run**: + +```bash +$ javac RetrievingAllDocuments.java +$ java RetrievingAllDocuments +``` + +**Output**: + +``` +Connected to the database successfully +Collection sampleCollection selected successfully +Document{{_id=5dce4e9ff68a9c2449e197b2, title=MongoDB, description=database, likes=100, url=http://www.tutorialspoint.com/mongodb/, by=tutorials point}} +Document{{_id=5dce4e9ff68a9c2449e197b3, title=RethinkDB, description=database, likes=200, url=http://www.tutorialspoint.com/rethinkdb/, by=tutorials point}} +``` + +## Update Document + +To update a document in the collection, use the `updateOne()` method of the `com.mongodb.client.MongoCollection` class. + +```java +import com.mongodb.client.FindIterable; +import com.mongodb.client.MongoCollection; +import com.mongodb.client.MongoDatabase; +import com.mongodb.client.model.Filters; +import com.mongodb.client.model.Updates; +import java.util.Iterator; +import org.bson.Document; +import com.mongodb.MongoClient; +import com.mongodb.MongoCredential; + +public class UpdatingDocuments { + public static void main( String args[] ) { + // Creating a Mongo client + MongoClient mongo = new Mongo + +Client( "localhost" , 27017 ); + + // Creating Credentials + MongoCredential credential; + credential = MongoCredential.createCredential("sampleUser", "myDb", "password".toCharArray()); + System.out.println("Connected to the database successfully"); + + // Accessing the database + MongoDatabase database = mongo.getDatabase("myDb"); + + // Retrieving a collection + MongoCollection collection = database.getCollection("sampleCollection"); + System.out.println("Collection sampleCollection selected successfully"); + + // Updating the document + collection.updateOne(Filters.eq("title", "MongoDB"), Updates.set("likes", 150)); + System.out.println("Document updated successfully..."); + + // Retrieving the updated document + FindIterable iterDoc = collection.find(); + int i = 1; + + // Getting the iterator + Iterator it = iterDoc.iterator(); + while (it.hasNext()) { + System.out.println(it.next()); + i++; + } + } +} +``` + +**Compile and Run**: + +```bash +$ javac UpdatingDocuments.java +$ java UpdatingDocuments +``` + +**Output**: + +``` +Connected to the database successfully +Collection sampleCollection selected successfully +Document updated successfully... +Document{{_id=5dce4e9ff68a9c2449e197b2, title=MongoDB, description=database, likes=150, url=http://www.tutorialspoint.com/mongodb/, by=tutorials point}} +Document{{_id=5dce4e9ff68a9c2449e197b3, title=RethinkDB, description=database, likes=200, url=http://www.tutorialspoint.com/rethinkdb/, by=tutorials point}} +``` + +## Delete Document + +To delete a document in the collection, use the `deleteOne()` method of the `com.mongodb.client.MongoCollection` class. + +```java +import com.mongodb.client.FindIterable; +import com.mongodb.client.MongoCollection; +import com.mongodb.client.MongoDatabase; +import com.mongodb.client.model.Filters; +import java.util.Iterator; +import org.bson.Document; +import com.mongodb.MongoClient; +import com.mongodb.MongoCredential; + +public class DeletingDocuments { + public static void main( String args[] ) { + // Creating a Mongo client + MongoClient mongo = new MongoClient( "localhost" , 27017 ); + + // Creating Credentials + MongoCredential credential; + credential = MongoCredential.createCredential("sampleUser", "myDb", "password".toCharArray()); + System.out.println("Connected to the database successfully"); + + // Accessing the database + MongoDatabase database = mongo.getDatabase("myDb"); + + // Retrieving a collection + MongoCollection collection = database.getCollection("sampleCollection"); + System.out.println("Collection sampleCollection selected successfully"); + + // Deleting the document + collection.deleteOne(Filters.eq("title", "MongoDB")); + System.out.println("Document deleted successfully..."); + + // Retrieving the updated documents + FindIterable iterDoc = collection.find(); + int i = 1; + + // Getting the iterator + Iterator it = iterDoc.iterator(); + while (it.hasNext()) { + System.out.println(it.next()); + i++; + } + } +} +``` + +**Compile and Run**: + +```bash +$ javac DeletingDocuments.java +$ java DeletingDocuments +``` + +**Output**: + +``` +Connected to the database successfully +Collection sampleCollection selected successfully +Document deleted successfully... +Document{{_id=5dce4e9ff68a9c2449e197b3, title=RethinkDB, description=database, likes=200, url=http://www.tutorialspoint.com/rethinkdb/, by=tutorials point}} +``` + +## Conclusion + +This tutorial covers basic operations with MongoDB using Java. With this knowledge, you can connect to a MongoDB database, create and retrieve collections, insert, update, and delete documents in your Java applications. + +## Diagram + +Below is a diagram illustrating the MongoDB Java process. + +```mermaid +graph TD; + A[Create MongoDB Client] --> B[Connect to Database] + B --> C[Create Collection] + C --> D[Insert Document] + D --> E[Retrieve Document] + E --> F[Update Document] + F --> G[Delete Document] + G --> H[Close MongoDB Client] +``` + +:::note + +- Ensure MongoDB is running before executing the Java programs. +- Use appropriate exception handling in real-world applications to handle any database connection issues. +- For more advanced usage and configurations, refer to the [MongoDB Java Driver Documentation](https://mongodb.github.io/mongo-java-driver/). +::: + +## Table of Methods + +| Method | Description | +|-----------------------|-------------------------------------------------------------| +| `createCollection` | Creates a new collection in the database | +| `getCollection` | Retrieves an existing collection from the database | +| `insertOne` | Inserts a single document into the collection | +| `find` | Retrieves documents from the collection | +| `updateOne` | Updates a single document in the collection | +| `deleteOne` | Deletes a single document from the collection | diff --git a/docs/MongoDB/mongodb-php.md b/docs/MongoDB/mongodb-php.md new file mode 100644 index 000000000..13ed0cf18 --- /dev/null +++ b/docs/MongoDB/mongodb-php.md @@ -0,0 +1,258 @@ +--- +id: mongodb-php +title: MongoDB - PHP +sidebar_label: PHP +sidebar_position: 25 +tags: [mongodb, php, connection, collection, document] +description: Learn how to use MongoDB with PHP including connection setup, creating collections, inserting, updating, finding, and deleting documents. +--- + +## MongoDB - PHP + +To use MongoDB with PHP, you need to use MongoDB PHP driver. Download the driver from the [MongoDB PHP Driver download page](https://www.php.net/manual/en/mongodb.installation.php). Make sure to download the latest release of it. Now unzip the archive and put `php_mongo.dll` in your PHP extension directory (`ext` by default) and add the following line to your `php.ini` file: + +```ini +extension = php_mongo.dll +``` + +### Make a Connection and Select a Database + +To make a connection, you need to specify the database name. If the database doesn't exist, MongoDB creates it automatically. + +Following is the code snippet to connect to the database: + +```php +mydb; + + echo "Database mydb selected"; +?> +``` + +When the program is executed, it will produce the following result: + +``` +Connection to database successfully +Database mydb selected +``` + +### Create a Collection + +Following is the code snippet to create a collection: + +```php +mydb; + echo "Database mydb selected"; + $collection = $db->createCollection("mycol"); + echo "Collection created successfully"; +?> +``` + +When the program is executed, it will produce the following result: + +``` +Connection to database successfully +Database mydb selected +Collection created successfully +``` + +### Insert a Document + +To insert a document into MongoDB, `insert()` method is used. + +Following is the code snippet to insert a document: + +```php +mydb; + echo "Database mydb selected"; + $collection = $db->mycol; + echo "Collection selected successfully"; + + $document = array( + "title" => "MongoDB", + "description" => "database", + "likes" => 100, + "url" => "http://www.tutorialspoint.com/mongodb/", + "by" => "tutorials point" + ); + + $collection->insert($document); + echo "Document inserted successfully"; +?> +``` + +When the program is executed, it will produce the following result: + +``` +Connection to database successfully +Database mydb selected +Collection selected successfully +Document inserted successfully +``` + +### Find All Documents + +To select all documents from the collection, `find()` method is used. + +Following is the code snippet to select all documents: + +```php +mydb; + echo "Database mydb selected"; + $collection = $db->mycol; + echo "Collection selected successfully"; + $cursor = $collection->find(); + // iterate cursor to display title of documents + + foreach ($cursor as $document) { + echo $document["title"] . "\n"; + } +?> +``` + +When the program is executed, it will produce the following result: + +``` +Connection to database successfully +Database mydb selected +Collection selected successfully +title: MongoDB +``` + +### Update a Document + +To update a document, you need to use the `update()` method. + +In the following example, we will update the title of the inserted document to MongoDB Tutorial. Following is the code snippet to update a document: + +```php +mydb; + echo "Database mydb selected"; + $collection = $db->mycol; + echo "Collection selected successfully"; + // now update the document + $collection->update(array("title"=>"MongoDB"), + array('$set'=>array("title"=>"MongoDB Tutorial"))); + echo "Document updated successfully"; + + // now display the updated document + $cursor = $collection->find(); + + // iterate cursor to display title of documents + echo "Updated document"; + + foreach ($cursor as $document) { + echo $document["title"] . "\n"; + } +?> +``` + +When the program is executed, it will produce the following result: + +``` +Connection to database successfully +Database mydb selected +Collection selected successfully +Document updated successfully +Updated document +title: MongoDB Tutorial +``` + +### Delete a Document + +To delete a document, you need to use the `remove()` method. + +In the following example, we will remove the documents that have the title MongoDB Tutorial. Following is the code snippet to delete a document: + +```php +mydb; + echo "Database mydb selected"; + $collection = $db->mycol; + echo "Collection selected successfully"; + + // now remove the document + $collection->remove(array("title"=>"MongoDB Tutorial"), false); + echo "Documents deleted successfully"; + + // now display the available documents + $cursor = $collection->find(); + + // iterate cursor to display title of documents + echo "Updated document"; + + foreach ($cursor as $document) { + echo $document["title"] . "\n"; + } +?> +``` + +When the program is executed, it will produce the following result: + +``` +Connection to database successfully +Database mydb selected +Collection selected successfully +Documents deleted successfully +Updated document +``` + +In the above example, the second parameter is a boolean type and used for the `justOne` field of the `remove()` method. + +Remaining MongoDB methods such as `findOne()`, `save()`, `limit()`, `skip()`, `sort()` etc., work the same way as explained above. + +```mermaid +graph TD; + A[Start] --> B[Connect to MongoDB]; + B --> C[Select Database]; + C --> D[Create Collection]; + D --> E[Insert Document]; + E --> F[Find Documents]; + F --> G[Update Document]; + G --> H[Delete Document]; + H --> I[End]; +``` + +| Step | Description | +|----------------------|----------------------------------------------------------| +| Connect to MongoDB | Establish a connection to the MongoDB server. | +| Select Database | Choose the database to work with. | +| Create Collection | Create a new collection within the selected database. | +| Insert Document | Add a new document to the collection. | +| Find Documents | Retrieve documents from the collection. | +| Update Document | Modify existing documents in the collection. | +| Delete Document | Remove documents from the collection. | \ No newline at end of file diff --git a/docs/MongoDB/mongodb-sharding.md b/docs/MongoDB/mongodb-sharding.md new file mode 100644 index 000000000..523a00b0d --- /dev/null +++ b/docs/MongoDB/mongodb-sharding.md @@ -0,0 +1,67 @@ +--- +id: mongodb-sharding +title: MongoDB - Sharding +sidebar_label: Sharding +sidebar_position: 21 +tags: [mongodb, sharding, database, horizontal scaling] +description: Learn about MongoDB sharding, its benefits, how it works, and the components involved in a sharded cluster. +--- + +# MongoDB - Sharding + +Sharding is the process of storing data records across multiple machines and is MongoDB's approach to handling data growth. As data size increases, a single machine may not suffice for storage and throughput requirements. Sharding addresses this through horizontal scaling, allowing more machines to support data growth and read/write operations. + +## Why Sharding? + +- In replication, all writes go to the master node. +- Latency-sensitive queries still go to the master. +- A single replica set is limited to 12 nodes. +- Memory may not be large enough for a large active dataset. +- Local disks may not be big enough. +- Vertical scaling is too expensive. + +## Sharding in MongoDB + +The following diagram illustrates MongoDB sharding using a sharded cluster: + +```mermaid +graph TD; + A[Client Applications] --> B[Query Routers] + B --> C[Shard 1] + B --> D[Shard 2] + B --> E[Shard N] + C --> F[Config Servers] + D --> F + E --> F +``` + +### Components of Sharding + +1. **Shards**: Store data and provide high availability and data consistency. Each shard is a separate replica set in production environments. +2. **Config Servers**: Store the cluster's metadata, containing mappings of the cluster's dataset to the shards. This metadata is used by the query router to direct operations to specific shards. Sharded clusters have exactly 3 config servers in production. +3. **Query Routers**: Interface with client applications, directing operations to the appropriate shard. They process and target operations to shards, returning results to clients. A sharded cluster can have multiple query routers to distribute the client request load. + +## Advantages of Sharding + +| Advantages | Description | +|---------------------------|-------------| +| Scalability | Sharding provides horizontal scalability by distributing data across multiple machines. | +| High Availability | Sharded clusters can continue to function even if some shards become unavailable. | +| Improved Performance | By distributing data and queries across multiple shards, sharding can improve read and write performance. | +| Cost-Effective | Horizontal scaling with sharding is often more cost-effective than vertical scaling. | + +## How Sharding Works + +When a client application sends a query, the query router directs the query to the appropriate shard based on the cluster's metadata stored in the config servers. Each shard processes the query and returns the result to the query router, which then sends the aggregated result back to the client. + +### Setting Up Sharding + +To set up sharding in MongoDB, you need to: + +1. Start config servers. +2. Start query routers. +3. Add shards to the cluster. +4. Enable sharding for a specific database. +5. Shard collections within the database. + +Sharding in MongoDB provides a robust solution for managing large datasets and high-throughput operations by distributing the load across multiple machines. \ No newline at end of file