Skip to content

PiyushAST/nosql-database-mongodb

Repository files navigation

MongoDB Resources and Examples

License: MIT Maintenance PRs Welcome

This repository provides a curated collection of resources and practical examples to help you learn and effectively use MongoDB, the leading NoSQL document database. Whether you're a beginner exploring NoSQL or an experienced developer looking for specific solutions, this repository aims to be a valuable resource for your MongoDB journey.

Table of Contents

  1. Overview of NoSQL Database MongoDB
  2. Files in This Repository
  3. Getting Started/Quick Start
  4. Usage Examples
  5. Related Blog Posts
  6. Contributing Guidelines
  7. License Information

Overview of NoSQL Database MongoDB

MongoDB is a popular, open-source, document-oriented NoSQL database designed for scalability and flexibility. It stores data in JSON-like documents, making it intuitive for developers and allowing for dynamic and evolving schemas.

Key Features:

  • Document-Oriented: Stores data in flexible, JSON-like documents.
  • Scalable: Designed for horizontal scalability, allowing you to handle large datasets and high traffic.
  • Flexible Schema: No need to predefine schemas, making it easier to adapt to changing data requirements.
  • High Performance: Optimized for performance with features like indexing and aggregation pipelines.
  • Open Source: Free to use and modify under the terms of the Server Side Public License (SSPL).
  • Rich Query Language: Powerful query language for retrieving and manipulating data.
  • Aggregation Framework: Provides powerful data aggregation capabilities.
  • Geospatial Indexing: Supports geospatial indexing and querying for location-based applications.

MongoDB is ideal for applications that require:

  • Flexible data models
  • Scalability
  • High performance
  • Rapid development

Files in This Repository

This repository contains a variety of files designed to help you learn and use MongoDB. Here's a breakdown of the contents:

  • ./connection.js (or equivalent): Contains code to establish a connection to a MongoDB database. It often includes configurations like the database URL, username, and password (ensure sensitive information is handled securely, preferably using environment variables).
  • ./schemas/: This directory holds schema definitions for your MongoDB collections. Schemas can be defined using Mongoose (an ODM) or directly using MongoDB's schema validation features. Example schemas might include user.js, product.js, etc.
  • ./examples/: This directory provides practical examples of common MongoDB operations, such as:
    • ./examples/insert_document.js: Demonstrates how to insert a new document into a collection.
    • ./examples/query_documents.js: Shows how to query documents based on various criteria.
    • ./examples/update_documents.js: Illustrates how to update existing documents.
    • ./examples/delete_documents.js: Demonstrates how to delete documents from a collection.
    • ./examples/aggregate_data.js: Shows how to use the aggregation framework to perform complex data analysis.
  • ./scripts/: Contains utility scripts for database management tasks, such as seeding the database with initial data (./scripts/seed_database.js) or backing up/restoring the database.
  • ./.env.example: A template .env file showing the environment variables required to run the examples. Important: Never commit your actual .env file with sensitive credentials.
  • ./README.md: This file - provides an overview of the repository, instructions on how to get started, and other helpful information.
  • ./LICENSE: Contains the licensing information for the repository (e.g., MIT License).
  • ./.gitignore: Specifies intentionally untracked files that Git should ignore. This typically includes files like .env, node_modules, and other temporary files.
  • ./package.json: Specifies project metadata, dependencies, and scripts for Node.js projects using MongoDB.
  • ./package-lock.json: Records the exact versions of dependencies used in the project.

Getting Started/Quick Start

Follow these steps to get started with the examples in this repository:

  1. Prerequisites:

    • MongoDB Installation: Ensure you have MongoDB installed and running on your local machine or a remote server. Download the appropriate version for your operating system from the official MongoDB website.
    • Node.js and npm (Optional): If the examples require Node.js, make sure you have it installed. Download from Node.js website. npm (Node Package Manager) is typically included with Node.js.
  2. Clone the Repository:

    git clone https://github.com/your-username/your-repo-name.git
    cd your-repo-name
  3. Install Dependencies (If applicable - Node.js):

    If the project uses Node.js and has a package.json file, run:

    npm install
  4. Configure Environment Variables:

    Create a .env file in the root directory of the project. Copy the contents of .env.example and fill in the appropriate values for your MongoDB connection:

    MONGODB_URI=mongodb://localhost:27017/your_database_name
    # Add other necessary environment variables here
    

    Important: Replace mongodb://localhost:27017/your_database_name with your actual MongoDB connection string.

  5. Run the Examples:

    Navigate to the examples/ directory and run the desired example file using Node.js (if applicable):

    cd examples
    node insert_document.js  # Example: Run the insert_document.js example

    Or, if the examples are shell scripts using mongo command line tool, you can run them like this:

    mongo insert_document.js
  6. Explore the Code:

    Open the example files in your code editor and explore the code to understand how they work. Modify the code to experiment with different MongoDB features and operations.

Usage Examples

This section provides more detailed examples of common MongoDB operations. Refer to the files in the examples/ directory for complete and runnable code.

Example 1: Inserting a Document

// Example using Node.js and the MongoDB driver
const { MongoClient } = require('mongodb');
require('dotenv').config(); // Load environment variables

async function main() {
  const uri = process.env.MONGODB_URI;
  const client = new MongoClient(uri);

  try {
    await client.connect();
    console.log("Connected to MongoDB");

    const database = client.db("your_database_name");
    const collection = database.collection("your_collection_name");

    const doc = {
      name: "John Doe",
      age: 30,
      city: "New York"
    };

    const result = await collection.insertOne(doc);
    console.log(`A document was inserted with the _id: ${result.insertedId}`);

  } finally {
    await client.close();
  }
}

main().catch(console.dir);

Example 2: Querying Documents

// Example using Node.js and the MongoDB driver
const { MongoClient } = require('mongodb');
require('dotenv').config(); // Load environment variables

async function main() {
  const uri = process.env.MONGODB_URI;
  const client = new MongoClient(uri);

  try {
    await client.connect();
    console.log("Connected to MongoDB");

    const database = client.db("your_database_name");
    const collection = database.collection("your_collection_name");

    const query = { city: "New York" };
    const options = {
      // sort returned documents in ascending order by name (A->Z)
      sort: { name: 1 },
      // Include only the `name` and `age` fields in each returned document
      projection: { _id: 0, name: 1, age: 1 },
    };

    const cursor = collection.find(query, options);

    if ((await cursor.countDocuments()) === 0) {
      console.log("No documents found!");
    }

    // replace console.dir with your callback to access individual documents
    await cursor.forEach(console.dir);

  } finally {
    await client.close();
  }
}

main().catch(console.dir);

Example 3: Updating Documents

// Example using Node.js and the MongoDB driver
const { MongoClient } = require('mongodb');
require('dotenv').config(); // Load environment variables

async function main() {
    const uri = process.env.MONGODB_URI;
    const client = new MongoClient(uri);

    try {
        await client.connect();
        console.log("Connected to MongoDB");

        const database = client.db("your_database_name");
        const collection = database.collection("your_collection_name");

        const filter = { name: "John Doe" };
        const updateDoc = {
            $set: {
                age: 31,
            },
        };
        const result = await collection.updateOne(filter, updateDoc);
        console.log(
            `${result.matchedCount} document(s) matched the filter, updated ${result.modifiedCount} document(s)`,
        );

    } finally {
        await client.close();
    }
}

main().catch(console.dir);

These are just a few basic examples. Explore the other files in the examples/ directory to learn more about MongoDB's capabilities.

Related Blog Posts

Here are some related blog posts that provide further insights into NoSQL databases and MongoDB:

Contributing Guidelines

We welcome contributions to this repository! If you have improvements, bug fixes, or new examples to share, please follow these guidelines:

  1. Fork the Repository: Fork this repository to your own GitHub account.
  2. Create a Branch: Create a new branch for your changes: git checkout -b feature/your-feature-name or git checkout -b fix/your-bug-fix.
  3. Make Your Changes: Implement your changes, ensuring they are well-documented and follow best practices.
  4. Test Your Changes: Thoroughly test your changes to ensure they work as expected.
  5. Commit Your Changes: Commit your changes with clear and concise commit messages: git commit -m "Add a new example for aggregation"
  6. Push to Your Fork: Push your branch to your forked repository: git push origin feature/your-feature-name
  7. Create a Pull Request: Create a pull request from your branch to the main branch of this repository. Provide a detailed description of your changes in the pull request.

We will review your pull request and provide feedback. Thank you for your contributions!

License Information

This project is licensed under the MIT License. See the LICENSE file for more information.

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published