Wednesday, September 18, 2024

MongoDB

 Follow me


Introduction to MongoDB

MongoDB is a popular NoSQL (Not Only SQL) database designed for handling large volumes of unstructured data. Unlike traditional relational databases, MongoDB stores data in a flexible, JSON-like format called BSON (Binary JSON). This allows it to handle diverse data types and structures more efficiently.

NoSQL Database

NoSQL databases are a category of databases that do not use traditional relational table structures. Instead, they use various models such as key-value pairs, wide-columns, graphs, or documents. MongoDB is a document-oriented NoSQL database, meaning it stores data in documents (JSON/BSON format) rather than rows and columns.

Advantage over RDBMS

1. Flexibility: MongoDB’s schema is flexible, allowing you to store different types of data in the same collection. This is beneficial for applications with evolving data models.

2. Scalability: MongoDB is designed to scale horizontally, meaning you can distribute data across multiple servers. This is easier and often more cost-effective compared to scaling traditional relational databases.

3. Performance: MongoDB can offer faster read and write operations for certain types of queries and large datasets because of its indexing and data retrieval mechanisms.

4. Document-Oriented: Data is stored in a JSON-like format (BSON), which can be more intuitive for developers, especially when dealing with hierarchical or nested data.

MongoDB Data Types

In MongoDB, the primary data type is BSON, which extends JSON to support additional types. Here are some common data types:

  • String: "Hello, MongoDB!"
  • Integer: 42
  • Boolean: true or false
  • Array: [1, 2, 3, 4]
  • Object: {"name": "John", "age": 30}
  • Date: ISODate("2024-09-10T00:00:00Z")
  • ObjectId: Unique identifier for documents.

 

Install MongoDB

On Windows:

  1. Download the MongoDB installer from the official MongoDB website.
  2. Run the installer and follow the prompts.
  3. After installation, you can start MongoDB using the mongod command.

On macOS:

  1. Install Homebrew if you haven't already.
  2. Run the command: brew tap mongodb/brew
  3. Install MongoDB with: brew install mongodb-community

On Linux:

  1. Add the MongoDB repository to your package manager.
  2. Install MongoDB using your package manager (e.g., apt-get install mongodb).

MongoDB Data Modeling

In MongoDB, data modeling involves designing the structure of documents and collections to efficiently store and retrieve data. Here’s a simple example:

Scenario: You’re building a blog application. You want to store information about posts and comments.

Document Model:

  • Posts Collection:

json

 

{

  "_id": ObjectId("unique_id"),

  "title": "My First Post",

  "content": "This is the content of the post.",

  "author": "Author Name",

  "comments": [

    {

      "user": "Commenter Name",

      "comment": "Great post!",

      "date": ISODate("2024-09-10T00:00:00Z")

    }

  ],

  "date_created": ISODate("2024-09-10T00:00:00Z")

}

Explanation: In this model, each blog post is a single document in the Posts collection. Comments are embedded directly within the post document, which can be useful if you expect to frequently retrieve comments along with the post.

Summary

MongoDB is a flexible, scalable NoSQL database that stores data in a document-oriented format. It offers advantages over traditional relational databases, such as better handling of unstructured data and horizontal scalability. Key features include a flexible schema, various BSON data types, and easy installation on different platforms. Data modeling in MongoDB involves designing documents and collections to suit your application’s needs, often using nested documents for related data.


MongoDB Operators

1. Query & Projection Operators

Query Operators: These are used to filter the documents in a query.

·         $eq (Equal): Matches documents where the field value is equal to the specified value.

Json
 
{ "age": { "$eq": 25 } }

This query finds documents where the age field equals 25.

·         $gt (Greater Than): Matches documents where the field value is greater than the specified value.

Json
 
{ "age": { "$gt": 30 } }

This query finds documents where the age field is greater than 30.

·         $lt (Less Than): Matches documents where the field value is less than the specified value.

Json
 
{ "age": { "$lt": 20 } }

This query finds documents where the age field is less than 20.

Projection Operators: These control which fields are returned in the query results.

·         $include: Specifies the fields to include in the result.

Json
 
db.collection.find({}, { "name": 1, "age": 1 })

This projection includes only the name and age fields in the result.

·         $exclude: Specifies the fields to exclude from the result.

Json
 
db.collection.find({}, { "password": 0 })

This projection excludes the password field from the result.

2. MongoDB Update Operators

Update operators modify existing documents.

·         $set: Updates the value of a field.

Json
 
db.collection.updateOne(
  { "name": "John" },
  { "$set": { "age": 31 } }
)

This updates the age field to 31 for the document where name is "John".

·         $unset: Removes a field from a document.

Json
 
db.collection.updateOne(
  { "name": "John" },
  { "$unset": { "age": "" } }
)

This removes the age field from the document where name is "John".

·         $push: Adds an item to an array field.

Json
 
db.collection.updateOne(
  { "name": "John" },
  { "$push": { "hobbies": "reading" } }
)

This adds "reading" to the hobbies array for the document where name is "John".

·         $inc: Increments the value of a field by a specified amount.

Json
 
db.collection.updateOne(
  { "name": "John" },
  { "$inc": { "age": 1 } }
)

This increments the age field by 1 for the document where name is "John".

3. Aggregation Pipeline Stages

Aggregation pipelines are used to process data records and return computed results.

 

·         $match: Filters documents based on specified criteria.

Json
 
{ "$match": { "age": { "$gte": 18 } } }

This stage filters documents where the age is greater than or equal to 18.

·         $group: Groups documents by a specified field and applies aggregate functions.

Json
 
{ "$group": { "_id": "$department", "total": { "$sum": "$salary" } } }

This groups documents by department and calculates the total salary for each department.

·         $sort: Sorts documents by specified fields.

Json
 
{ "$sort": { "age": 1 } }

This sorts documents by age in ascending order (use -1 for descending).

·         $project: Reshapes each document, including only the specified fields.

Json
 
{ "$project": { "name": 1, "age": 1, "_id": 0 } }

This includes only the name and age fields in the output documents and excludes the _id field.

4. MongoDB limit()

Limits the number of documents returned by a query.

Json
 
db.collection.find().limit(5)

This returns only the first 5 documents from the collection.

5. MongoDB sort()

Sorts documents based on specified fields.

Json
 
db.collection.find().sort({ "age": -1 })

This sorts documents by the age field in descending order (use 1 for ascending).

6. Query Modifiers

$or: Matches documents where at least one of the conditions is true.

Json
 
db.collection.find({ "$or": [ { "age": { "$lt": 25 } }, { "name": "Alice" } ] })

This finds documents where age is less than 25 or name is "Alice".

$and: Matches documents where all conditions are true.

Json
 
db.collection.find({ "$and": [ { "age": { "$gt": 20 } }, { "status": "active" } ] })

This finds documents where age is greater than 20 and status is "active".

Summary

MongoDB provides a variety of operators for querying, updating, and aggregating data:

  • Query Operators like $eq, $gt, and $lt help in filtering documents based on field values.
  • Projection Operators such as $include and $exclude control which fields are returned in the query results.
  • Update Operators like $set, $unset, $push, and $inc modify existing documents.
  • Aggregation Pipeline Stages include $match, $group, $sort, and $project for processing and transforming data.
  • limit() restricts the number of documents returned.
  • sort() orders documents based on specified fields.
  • Query Modifiers like $or and $and combine multiple conditions for more complex queries.

MongoDB Database Commands

1. Aggregation Commands

Aggregation commands process data records and return computed results.

·         db.collection.aggregate(): Runs an aggregation pipeline on a collection.

Example:

Javascript
 
db.orders.aggregate([
  { $match: { status: "completed" } },
  { $group: { _id: "$customer", totalAmount: { $sum: "$amount" } } },
  { $sort: { totalAmount: -1 } }
])

This pipeline filters completed orders, groups by customer, calculates the total amount spent by each customer, and sorts the results in descending order of total amount.

2. Geospatial Commands

Geospatial commands handle spatial queries and indexing.

·         db.collection.find() with $geoNear: Finds documents near a specified location.

Example:

Javascript
 
db.places.find({
  location: {
    $near: {
      $geometry: { type: "Point", coordinates: [40.7128, -74.0060] },
      $maxDistance: 5000
    }
  }
})

This query finds places within 5,000 meters of the coordinates for New York City.

3. Query and Write Operation Commands

Commands for querying and writing data to collections.

·         db.collection.find(): Retrieves documents from a collection.

Example:

Javascript
 
db.users.find({ age: { $gte: 21 } })

Finds users who are 21 years old or older.

·         db.collection.insertOne(): Inserts a single document into a collection.

Example:

Javascript
 
db.products.insertOne({ name: "Laptop", price: 1200 })

Inserts a new product document with a name and price.

·         db.collection.updateOne(): Updates a single document.

Example:

Javascript
 
db.products.updateOne(
  { name: "Laptop" },
  { $set: { price: 1100 } }
)

Updates the price of the laptop to 1100.

·         db.collection.deleteOne(): Deletes a single document.

Example:

Javascript
 
db.products.deleteOne({ name: "Laptop" })

Deletes the document where the product name is "Laptop".

4. Query Plan Cache Commands

Commands for managing and analyzing query plans.

·         db.collection.explain(): Provides detailed information on how MongoDB executes a query.

Example:

Javascript
 
db.users.find({ age: { $gte: 21 } }).explain("executionStats")

Shows the query execution plan and statistics for finding users 21 years old or older.

·         db.collection.stats(): Returns statistics about the collection.

Example:

Javascript
 
db.users.stats()

Provides statistics about the users collection, such as size and number of documents.

5. Authentication Commands

Commands for managing authentication and access control.

·         db.runCommand({ ping: 1 }): Tests connectivity and authentication.

Example:

Javascript
 
db.runCommand({ ping: 1 })

Returns a response if the connection and authentication are successful.

·         db.runCommand({ createUser: "username", pwd: "password", roles: ["readWrite"] }): Creates a new user.

Example:

Javascript
 
db.runCommand({
  createUser: "johnDoe",
  pwd: "securePass",
  roles: ["readWrite"]
})

Creates a new user johnDoe with read and write permissions.

6. User Management Commands

Commands for managing database users.

·         db.getUsers(): Lists all users in the current database.

Example:

Javascript
 
db.getUsers()

Retrieves a list of all users in the database.

·         db.runCommand({ dropUser: "username" }): Deletes a user.

Example:

Javascript
 
db.runCommand({ dropUser: "johnDoe" })

Deletes the user johnDoe.

7. Role Management Commands

Commands for managing roles and permissions.

·         db.getRoles(): Lists all roles in the current database.

Example:

Javascript
 
db.getRoles()

Retrieves a list of all roles.

·         db.runCommand({ createRole: "roleName", privileges: [], roles: [] }): Creates a new role.

Example:

Javascript
 
db.runCommand({
  createRole: "customRole",
  privileges: [{ resource: { db: "test", collection: "" }, actions: ["find"] }],
  roles: []
})

Creates a new role customRole with find privileges on the test database.


8. Replication Commands

Commands related to replication and replica sets.

 

·         rs.status(): Provides the status of the replica set.

Example:

Javascript
 
rs.status()

Shows the status of the replica set, including the state of each member.

·         rs.initiate(): Initializes a new replica set.

Example:

Javascript
 
rs.initiate({
  _id: "myReplicaSet",
  members: [
    { _id: 0, host: "localhost:27017" }
  ]
})

Initializes a replica set with one member.

9. Sharding Commands

Commands related to sharding and managing shard clusters.

·         sh.status(): Provides the status of the sharded cluster.

Example:

Javascript
 
sh.status()

Displays information about the sharded cluster, including the state of shards and databases.

·         sh.shardCollection(): Shards a collection.

Example:

Javascript
 
sh.shardCollection("myDatabase.myCollection", { "field": 1 })

Shards the myCollection collection on the field field.

10. Session Commands

Commands for managing client sessions.

·         db.runCommand({ startSession: 1 }): Starts a new session.

Example:

Javascript
 
db.runCommand({ startSession: 1 })

Starts a new client session.

·         db.getSession(): Retrieves the current session.

Example:

Javascript
 
db.getSession()

Returns the current session information.

Summary

MongoDB offers a range of commands to interact with and manage databases effectively:

  • Aggregation Commands process and analyze data using pipelines.
  • Geospatial Commands handle spatial queries and indexing.
  • Query and Write Operation Commands manage data retrieval, insertion, updating, and deletion.
  • Query Plan Cache Commands help analyze and manage query execution plans.
  • Authentication Commands deal with user authentication and connectivity testing.
  • User Management Commands create, list, and delete database users.
  • Role Management Commands manage roles and their associated privileges.
  • Replication Commands monitor and configure replica sets.
  • Sharding Commands manage and configure sharded clusters.
  • Session Commands handle client sessions and their state.

MongoDB Database Operations

1. Create Database

In MongoDB, a database is created implicitly when you first store data in it. There is no explicit command to create a database before storing data. Instead, you create a database by switching to it and then inserting data into a collection.

Steps to Create a Database:

1.     Switch to the Database: Use the use command to switch to a database. If the database does not exist, MongoDB will create it when data is inserted.

Example:

Javascript
 
use myNewDatabase

This command switches to myNewDatabase. If myNewDatabase does not already exist, MongoDB will create it when you add data.

2.     Insert Data: Add data to a collection within this database. This action creates the database.

Example:

Javascript
 
db.myCollection.insertOne({ name: "Alice", age: 30 })

This inserts a document into myCollection in the myNewDatabase. If the database myNewDatabase did not exist before, it is now created with this collection.

2. Drop Database

To delete a database, you use the dropDatabase command. This removes the database and all of its collections.

Steps to Drop a Database:

1.     Switch to the Database: Ensure you are using the database you want to drop.

Example:

Javascript
 
use myNewDatabase

This command switches to myNewDatabase.

2.     Drop the Database: Use the dropDatabase command to delete the database.

Example:

Javascript
 
db.dropDatabase()

This command drops the myNewDatabase, including all collections and documents within it.

Summary

·         Create Database: In MongoDB, you create a database by switching to it using use <databaseName> and then adding data to it. The database is not actually created until the first collection is created and populated with data.

·         Drop Database: To remove a database, switch to it using use <databaseName> and then execute db.dropDatabase(). This deletes the database and all of its contents permanently.

MongoDB Collection Operations

1. Create Collection

In MongoDB, collections are created implicitly when you first insert a document into them. However, you can also explicitly create a collection using the createCollection command if you need to specify options like validation rules or capped collections.

Implicit Creation:

1.     Insert Data: When you insert data into a collection that doesn’t exist, MongoDB automatically creates it.

Example:

Javascript
 
use myDatabase
db.myCollection.insertOne({ name: "John", age: 25 })

This command creates myCollection in myDatabase if it doesn’t already exist, and inserts a document into it.

Explicit Creation:

1.     Create Collection with Options: Use db.createCollection() to explicitly create a collection with specific options.

Example:

Javascript
 
use myDatabase
db.createCollection("myCollection", {
  capped: true,
  size: 100000,
  max: 5000
})

This creates a capped collection named myCollection in myDatabase with a maximum size of 100,000 bytes and a limit of 5,000 documents.

2. Drop Collection

To delete a collection and all of its documents, you use the drop() command. This operation removes the collection permanently.

Steps to Drop a Collection:

1.     Switch to the Database: Ensure you are using the database that contains the collection you want to drop.

Example:

Javascript
 
use myDatabase

This command switches to myDatabase.

2.     Drop the Collection: Use the drop() command on the collection you want to delete.

Example:

Javascript
 
db.myCollection.drop()

This command drops the myCollection collection from myDatabase, removing all documents and metadata associated with it.

Summary

·         Create Collection: Collections in MongoDB are automatically created when you insert the first document. You can also explicitly create a collection using db.createCollection() with additional options if needed, such as specifying a capped collection or validation rules.

·         Drop Collection: To delete a collection, use db.myCollection.drop(). This command removes the collection and all its documents from the database.


CRUD Operations on Documents

1. Insert Documents

Inserting a Single Document:

·         insertOne(): Adds a single document to a collection.

Example:

Javascript
 
db.users.insertOne({ name: "Alice", age: 30 })

This command inserts a new document with name "Alice" and age 30 into the users collection.

Inserting Multiple Documents:

·         insertMany(): Adds multiple documents to a collection.

Example:

Javascript
 
db.users.insertMany([
  { name: "Bob", age: 25 },
  { name: "Carol", age: 27 }
])

This command inserts two documents into the users collection.

2. Update Documents

Updating a Single Document:

·         updateOne(): Updates the first document that matches a filter.

Example:

Javascript
 
db.users.updateOne(
  { name: "Alice" },
  { $set: { age: 31 } }
)

This command updates the age field to 31 for the document where name is "Alice".

Updating Multiple Documents:

·         updateMany(): Updates all documents that match the filter.

Example:

Javascript
 
db.users.updateMany(
  { age: { $lt: 30 } },
  { $set: { status: "young" } }
)

This command sets the status field to "young" for all documents where age is less than 30.

3. Delete Documents

Deleting a Single Document:

·         deleteOne(): Deletes the first document that matches a filter.

Example:

Javascript
 
db.users.deleteOne({ name: "Bob" })

This command deletes the document where name is "Bob".

Deleting Multiple Documents:

·         deleteMany(): Deletes all documents that match the filter.

Example:

Javascript
 
db.users.deleteMany({ age: { $lt: 30 } })

This command deletes all documents where age is less than 30.

4. Query Documents

Basic Query:

·         find(): Retrieves documents that match a filter.

Example:

Javascript
 
db.users.find({ age: { $gte: 30 } })

This command finds all documents where age is greater than or equal to 30.

Query with Projection:

·         find() with Projection: Returns only specified fields.

Example:

Javascript
 
db.users.find({ age: { $gte: 30 } }, { name: 1, _id: 0 })

This command returns only the name field for documents where age is 30 or older, excluding the _id field.

5. SQL to MongoDB Mapping

Mapping SQL to MongoDB:

·         SQL SELECT * FROM table WHERE condition;
MongoDB: db.collection.find({ condition })

·         SQL UPDATE table SET field=value WHERE condition;
MongoDB: db.collection.updateMany({ condition }, { $set: { field: value } })

·         SQL DELETE FROM table WHERE condition;
MongoDB: db.collection.deleteMany({ condition })

·         SQL INSERT INTO table (field1, field2) VALUES (value1, value2);
MongoDB: db.collection.insertOne({ field1: value1, field2: value2 })

6. MongoDB Text Search

Text Search: Allows searching for text in string fields.

·         Create a Text Index:

Javascript
 
db.articles.createIndex({ content: "text" })

·         Perform a Text Search:

Javascript
 
db.articles.find({ $text: { $search: "MongoDB" } })

This command finds documents in the articles collection where the content field contains the word "MongoDB".

7. Partial Updates & Document Limits

Partial Updates: Use $set, $unset, and other operators to update specific fields.

  • Example:
Javascript
 
db.users.updateOne(
  { name: "Alice" },
  { $set: { email: "alice@example.com" } }
)

Document Limits: MongoDB documents have a size limit of 16 MB.

8. Removing Documents

Remove Specific Documents:

·         remove(): Legacy method to remove documents, replaced by deleteOne() and deleteMany().

Example:

Javascript
 
db.users.remove({ age: { $lt: 30 } })

This removes documents where age is less than 30.

9. Multi Update

Update Multiple Documents:

·         updateMany(): Updates all documents matching the filter.

Example:

Javascript
 
db.users.updateMany(
  { status: "inactive" },
  { $set: { status: "active" } }
)

This command updates the status field to "active" for all documents where status was "inactive".

10. Upsert

Upsert: Update a document if it exists, or insert it if it doesn’t.

 

  • Example:
Javascript
 
db.users.updateOne(
  { name: "Alice" },
  { $set: { age: 31 } },
  { upsert: true }
)

This command updates age for "Alice" if she exists, or inserts a new document if she doesn’t.

11. Wire Protocol

Wire Protocol: MongoDB uses a binary protocol to communicate between clients and servers, handling operations and queries.

12. Bulk Operations and Methods

Bulk Operations: Execute multiple write operations in bulk for efficiency.

  • Example:
Javascript
 
var bulk = db.users.initializeOrderedBulkOp();
bulk.insert({ name: "Eve", age: 22 });
bulk.find({ name: "Alice" }).update({ $set: { age: 32 } });
bulk.execute();

This example performs an ordered bulk operation to insert a new document and update an existing document in one batch.

13. Common Commands

db.runCommand(): Executes database commands directly.

  • Example:
Javascript
 
db.runCommand({ collMod: "users", validator: { $jsonSchema: { bsonType: "object", required: ["name"], properties: { name: { bsonType: "string" } } } } })

This command modifies the collection users to enforce a schema validation rule.

db.isMaster(): Provides information about the current server's role in a replica set.

  • Example:
Javascript
 
db.isMaster()

Returns the status of the server (primary, secondary, etc.).

db.serverStatus(): Provides server statistics.

  • Example:
Javascript
 
db.serverStatus()

Returns detailed information about the server’s status.

db.currentOp() & db.killOp(): Manage and control ongoing operations.

·         db.currentOp(): Lists currently running operations.

Example:

Javascript
 
db.currentOp()

·         db.killOp(): Terminates a specified operation.

Example:

Javascript
 
db.killOp(opid)

Kills the operation with the given opid.

collection.stats() & collection.drop(): Manage collection statistics and deletion.

·         collection.stats(): Provides statistics about a collection.

Example:

Javascript
 
db.users.stats()

·         collection.drop(): Deletes a collection.

Example:

Javascript
 
db.users.drop()

Summary

  • Insert Documents: Use insertOne() or insertMany() to add documents to a collection.
  • Update Documents: Modify existing documents with updateOne(), updateMany(), or partial updates using operators.
  • Delete Documents: Remove documents with deleteOne() or deleteMany().
  • Query Documents: Retrieve documents with find() and apply projections as needed.
  • SQL to MongoDB Mapping: Translate SQL operations to MongoDB equivalents.
  • MongoDB Text Search: Use text indexes and $text queries for searching text.
  • Partial Updates & Document Limits: Perform partial updates with operators and be aware of the 16 MB document size limit.
  • Removing Documents: Use deleteOne() and deleteMany() to remove documents.
  • Multi Update: Update multiple documents at once with updateMany().
  • Upsert: Update or insert documents using the upsert option.
  • Wire Protocol: Understand that MongoDB uses a binary protocol for client-server communication.
  • Bulk Operations and Methods: Perform bulk operations for efficiency.
  • Common Commands: Use db.runCommand(), `db.isMaster()

MongoDB Shell

The MongoDB Shell (mongosh) is an interactive JavaScript interface for MongoDB. It allows you to interact with your MongoDB database, execute queries, and perform administrative tasks.

1. MongoDB Shell

The MongoDB Shell (mongosh) provides a command-line interface to interact with MongoDB. It replaces the older mongo shell with a more modern and user-friendly environment.

Starting the Shell:

  • Command:
Bash
 
mongosh

Connecting to a Database:

  • Command:
Bash
 
mongosh "mongodb://localhost:27017/myDatabase"

Connects to the myDatabase database on the local MongoDB server.

2. Shell Collection Methods

MongoDB Shell provides various methods to interact with collections.

·         db.collection.find(): Retrieves documents from a collection.

Example:

Javascript
 
db.users.find({ age: { $gte: 30 } })

·         db.collection.insertOne(): Inserts a single document.

Example:

Javascript
 
db.users.insertOne({ name: "Jane", age: 28 })

·         db.collection.updateOne(): Updates a single document.

Example:

Javascript
 
db.users.updateOne(
  { name: "Jane" },
  { $set: { age: 29 } }
)

·         db.collection.deleteOne(): Deletes a single document.

Example:

Javascript
 
db.users.deleteOne({ name: "Jane" })

3. Cursor Methods

When you query documents, MongoDB returns a cursor object that you can use to iterate over results.

·         forEach(): Iterates over the documents in the cursor.

Example:

Javascript
 
db.users.find().forEach(doc => printjson(doc))

·         toArray(): Converts the cursor to an array of documents.

Example:

Javascript
 
var users = db.users.find().toArray()

·         next(): Retrieves the next document in the cursor.

Example:

Javascript
 
var cursor = db.users.find()
var firstDoc = cursor.next()

4. MongoDB Database Commands

Database Commands are used to perform administrative tasks.

·         db.runCommand(): Executes a command directly on the database.

 

 

Example:

Javascript
 
db.runCommand({ serverStatus: 1 })

This command retrieves server status information.

·         db.stats(): Provides statistics about the database.

Example:

Javascript
 
db.stats()

Returns statistics like database size, number of collections, etc.

5. Query Plan Cache Methods

Methods for managing the query plan cache, which stores execution plans for queries.

·         db.collection.explain(): Provides details about how MongoDB executes a query.

Example:

Javascript
 
db.users.find({ age: { $gte: 30 } }).explain("executionStats")

Returns the query execution plan with execution statistics.

6. User Management Method

User Management Methods handle creating and managing database users.

·         db.createUser(): Creates a new user.

Example:

Javascript
 
db.createUser({
  user: "newUser",
  pwd: "password123",
  roles: [{ role: "readWrite", db: "myDatabase" }]
})

·         db.dropUser(): Deletes an existing user.

Example:

Javascript
 
db.dropUser("newUser")

·         db.getUsers(): Lists all users in the current database.

Example:

Javascript
 
db.getUsers()
 

7. Role Management Method

Role Management Methods handle the creation and management of roles.

·         db.createRole(): Creates a new role.

Example:

Javascript
 
db.createRole({
  role: "customRole",
  privileges: [{ resource: { db: "myDatabase", collection: "" }, actions: ["find"] }],
  roles: []
})

·         db.dropRole(): Deletes an existing role.

Example:

Javascript
 
db.dropRole("customRole")

·         db.getRoles(): Lists all roles in the current database.

Example:

Javascript
 
db.getRoles()
 

8. MongoDB Replication Methods

Replication Methods are used to manage replica sets.

·         rs.status(): Provides the status of the replica set.

Example:

Javascript
 
rs.status()

·         rs.initiate(): Initializes a new replica set.

Example:

Javascript
 
rs.initiate({
  _id: "myReplicaSet",
  members: [
    { _id: 0, host: "localhost:27017" }
  ]
})

·         rs.stepDown(): Forces the current primary to step down.

Example:

Javascript
 
rs.stepDown()

Summary

  • MongoDB Shell: Provides an interactive JavaScript interface for MongoDB, allowing you to run commands and queries directly.
  • Shell Collection Methods: Includes methods for inserting, updating, deleting, and querying documents.
  • Cursor Methods: Allows iteration over query results, including methods like forEach(), toArray(), and next().
  • MongoDB Database Commands: Use commands like db.runCommand() and db.stats() for administrative tasks.
  • Query Plan Cache Methods: Methods such as db.collection.explain() help analyze query execution plans.
  • User Management Method: Manage users with commands like db.createUser() and db.dropUser().
  • Role Management Method: Manage roles using commands like db.createRole() and db.dropRole().
  • MongoDB Replication Methods: Includes methods to manage replica sets, such as rs.status() and rs.initiate().

MongoDB Cloud Services

MongoDB offers several cloud-based tools and platforms to manage and operate MongoDB deployments. These services help with various aspects such as database hosting, monitoring, and management.

1. MongoDB Stitch (Now Part of MongoDB Realm)

MongoDB Stitch was the serverless platform that has been integrated into MongoDB Realm. It provides backend services for applications, such as data access, authentication, and functions.

  • Key Features:
    • Authentication: Supports various authentication methods including email/password, API keys, and social providers like Google and Facebook.
    • Data Access: Provides easy access to MongoDB data from your applications with built-in SDKs.
    • Functions: Allows running serverless functions triggered by database changes or HTTP requests.

Example:

Suppose you want to use MongoDB Realm to add authentication to your app. You might configure a Realm app with email/password authentication and then use the Realm SDK in your client application to handle user sign-up and login.

Javascript
 
// Example using Realm SDK for authentication
const app = new Realm.App({ id: "<your-realm-app-id>" });
const credentials = Realm.Credentials.emailPassword("user@example.com", "password123");
 
app.logIn(credentials)
  .then(user => {
    console.log("Logged in as", user.profile.email);
  })
  .catch(err => {
    console.error("Failed to log in", err);
  });
 

2. MongoDB Atlas

MongoDB Atlas is MongoDB’s fully managed cloud database service. It provides a scalable and secure database-as-a-service on popular cloud providers like AWS, Google Cloud, and Microsoft Azure.

  • Key Features:
    • Managed Service: Automated backups, scaling, and patching.
    • Security: Advanced security features including encryption at rest and in transit.
    • Monitoring: Built-in performance monitoring and alerting.
    • Global Distribution: Easy setup for global databases with multiple geographic regions.

Example:

To create a new cluster in MongoDB Atlas, you would:

  1. Log in to your Atlas account.
  2. Navigate to the Clusters section and click on Build a Cluster.
  3. Select the cloud provider and region, then configure the cluster settings.
  4. Click Create Cluster to deploy your database.

You can then connect to your Atlas cluster from your application using connection strings provided in the Atlas UI.

3. MongoDB Cloud Manager

MongoDB Cloud Manager is a cloud-based management platform for MongoDB. It provides tools for monitoring, backups, and automation of MongoDB deployments. Cloud Manager is designed for users who manage their own MongoDB instances.

  • Key Features:
    • Monitoring: Detailed metrics and dashboards for performance monitoring.
    • Backups: Automated backups and restore functionality.
    • Automation: Automated provisioning and configuration management.

Example:

To set up monitoring for your MongoDB deployment in Cloud Manager:

  1. Log in to Cloud Manager.
  2. Go to the Monitoring section.
  3. Add your MongoDB instances to be monitored.
  4. Configure alerts and dashboards to track performance metrics.

4. MongoDB Ops Manager

MongoDB Ops Manager is an on-premises management platform for MongoDB, offering similar features to Cloud Manager but designed to be installed and run within your own infrastructure.

  • Key Features:
    • Monitoring: In-depth monitoring and alerting for MongoDB deployments.
    • Backup: Comprehensive backup solutions, including point-in-time recovery.
    • Automation: Tools for deploying and managing MongoDB clusters.

Example:

To deploy and configure Ops Manager:

  1. Install Ops Manager on your infrastructure.
  2. Configure the Ops Manager to connect to your MongoDB deployments.
  3. Use the Ops Manager UI to manage backups, monitor cluster performance, and automate deployments.

Summary

  • MongoDB Stitch (MongoDB Realm): Provides serverless backend services such as authentication, data access, and functions, integrated into MongoDB Realm.
  • MongoDB Atlas: A fully managed cloud database service offering automated scaling, security, and monitoring on cloud platforms like AWS, Google Cloud, and Azure.
  • MongoDB Cloud Manager: A cloud-based tool for managing MongoDB instances with features like monitoring, backups, and automation for self-managed deployments.
  • MongoDB Ops Manager: An on-premises management tool offering monitoring, backup, and automation features for MongoDB deployments within your infrastructure.

MongoDB Tools

MongoDB offers various tools to interact with and manage your MongoDB databases. Two important tools are MongoDB Compass and the MongoDB BI Connector.

1. MongoDB Compass

MongoDB Compass is the official graphical user interface (GUI) for MongoDB. It provides a user-friendly way to interact with your MongoDB databases, perform queries, and analyze data visually.

  • Key Features:
    • Schema Visualization: Displays the structure of your data and helps you understand the schema.
    • Query Building: Allows you to build and execute queries using a visual interface.
    • Index Management: View and manage indexes on your collections.
    • Aggregation Pipeline Builder: Create and test aggregation queries using a visual editor.

Example:

To use MongoDB Compass to view your data:

  1. Download and Install: Download MongoDB Compass from the MongoDB website and install it.
  2. Connect to a Database: Open Compass and enter your MongoDB connection string (e.g., mongodb://localhost:27017/myDatabase).
  3. Explore Collections: Select a database and then a collection to view documents, query data, and analyze schema.

 

For instance, if you want to find documents where age is greater than 30:

  • Go to the collection you’re interested in.
  • In the query bar, enter { age: { $gt: 30 } }.
  • Click Find to execute the query and view results.

2. MongoDB BI Connector

MongoDB BI Connector is a tool that allows you to use SQL-based business intelligence (BI) tools to query MongoDB data. It acts as a bridge between MongoDB and traditional SQL-based tools, enabling analytics and reporting.

  • Key Features:
    • SQL Interface: Provides a SQL interface to MongoDB collections.
    • Compatibility: Works with BI tools like Tableau, Microsoft Power BI, and Looker.
    • Real-time Analytics: Enables real-time data analysis using SQL.

Example:

To use the MongoDB BI Connector with a BI tool like Tableau:

  1. Install BI Connector: Follow the MongoDB documentation to install and configure the MongoDB BI Connector on your server.
  2. Configure the Connector: Set up the connector to point to your MongoDB instance by editing the mongosqld configuration file.
  3. Connect BI Tool: Open Tableau and create a new data source connection.
    • Select MongoDB BI Connector as the connection type.
    • Enter the connection details, such as the server address and port.
  4. Query Data: Use SQL queries to access and analyze MongoDB data within Tableau.

For instance, to query data from a collection named sales:

  • In Tableau, you might write a SQL query like:
Sql
 
SELECT * FROM sales WHERE amount > 1000

This query retrieves all documents from the sales collection where the amount field is greater than 1000.

Summary

  • MongoDB Compass: A GUI tool for MongoDB that provides schema visualization, query building, index management, and aggregation pipeline building. It simplifies interacting with MongoDB databases through a graphical interface.
  • MongoDB BI Connector: A tool that allows SQL-based BI tools to query MongoDB data. It provides a SQL interface for real-time analytics and reporting, making MongoDB data accessible through traditional SQL-based analysis tools.

Connectivity: Python MongoDB

Connecting to MongoDB from Python typically involves using the pymongo library, which is the official MongoDB driver for Python. It provides a way to interact with MongoDB databases using Python code.

1. Installing pymongo

Before you can use pymongo, you need to install it. You can do this using pip:

Bash
 
pip install pymongo

2. Connecting to MongoDB

To connect to a MongoDB database using pymongo, you need to create a client instance with a connection string or connection details.

Example: Connecting to a Local MongoDB Instance

Here’s a basic example of how to connect to a MongoDB instance running on your local machine:

Python
 
from pymongo import MongoClient
 
# Create a client instance
client = MongoClient('mongodb://localhost:27017/')
 
# Access a database
db = client.myDatabase
 
# Access a collection
collection = db.myCollection

In this example:

  • MongoClient is used to create a connection to the MongoDB server.
  • client.myDatabase accesses the myDatabase database.
  • db.myCollection accesses the myCollection collection within the database.

3. Performing CRUD Operations

Inserting Documents:

Python
 
# Insert a single document
collection.insert_one({"name": "Alice", "age": 30})
 
# Insert multiple documents
collection.insert_many([
    {"name": "Bob", "age": 25},
    {"name": "Carol", "age": 27}
])

Querying Documents:

Python
 
# Find a single document
document = collection.find_one({"name": "Alice"})
print(document)
 
# Find multiple documents
for doc in collection.find({"age": {"$gte": 25}}):
    print(doc)

Updating Documents:

Python
 
# Update a single document
collection.update_one({"name": "Alice"}, {"$set": {"age": 31}})
 
# Update multiple documents
collection.update_many({"age": {"$lt": 30}}, {"$set": {"status": "young"}})

Deleting Documents:

Python
 
# Delete a single document
collection.delete_one({"name": "Bob"})
 
# Delete multiple documents
collection.delete_many({"age": {"$lt": 30}})

4. Handling Connection to Remote MongoDB

If your MongoDB instance is hosted remotely (e.g., on MongoDB Atlas), you will need to use a connection string provided by your MongoDB hosting service.

Example: Connecting to MongoDB Atlas

Python
 
from pymongo import MongoClient
 
# Replace <username>, <password>, <cluster-address>, and <dbname> with your Atlas credentials and database name
connection_string = "mongodb+srv://<username>:<password>@<cluster-address>/<dbname>?retryWrites=true&w=majority"
client = MongoClient(connection_string)
 
# Access a database
db = client.myDatabase
 
# Access a collection
collection = db.myCollection

Summary

  • pymongo Library: Install it via pip to interact with MongoDB from Python.
  • Connecting to MongoDB: Use MongoClient with a connection string or connection details to connect to MongoDB.
  • CRUD Operations: Perform basic operations like inserting, querying, updating, and deleting documents using methods provided by pymongo.
  • Remote Connections: Use the appropriate connection string for cloud-hosted MongoDB services like MongoDB Atlas.

 

No comments:

Post a Comment

DSA using Python: Assignment 3 – Singly Linked List (SLL)

Follow Me About Singly Linked List In this assignment, we implement a Singly Linked List (SLL) using Python. We build the structure using cl...