diff --git a/blog/9-principles-of-good-web-design.md b/blog/9-principles-of-good-web-design.md deleted file mode 100644 index 89a9b6c4c..000000000 --- a/blog/9-principles-of-good-web-design.md +++ /dev/null @@ -1,128 +0,0 @@ ---- -slug: 9-principles-of-good-web-design -date: 2024-06-10 -title: "9 Principles of Good Web Design" -image: /img/codeharborhub-social-card.jpg -authors: [ajay-dhangar] -tags: [web-design, principles, ux, ui, design] -description: "Discover the 9 essential principles of good web design that enhance user experience and drive engagement. Learn how to create visually appealing, user-friendly websites that stand out." -sidebar_label: Web Design Principles ---- - -Creating a well-designed website is crucial for attracting and retaining visitors. Good web design not only enhances the visual appeal of a site but also improves its functionality and user experience. Here are nine essential principles of good web design that can help you create an effective and engaging website. - - - -## 1. Website Purpose - -Every website should have a clear purpose. Whether it's to inform, entertain, sell products, or provide services, the purpose should be evident to visitors within seconds of landing on the site. A well-defined purpose helps guide design decisions and ensures that all elements of the site work towards achieving that goal. - -**There are many purposes a website can have, including:** - -- **E-commerce**: Selling products or services online. -- **Portfolio**: Showcasing work or projects. -- **Blog**: Sharing articles, insights, or news. -- **Informational**: Providing information or resources on a specific topic. -- **Landing Page**: Promoting a specific product, service, or campaign. - -## 2. Simplicity - -Simplicity is key to effective web design. A cluttered or overly complex website can overwhelm visitors and make it difficult for them to find what they need. Focus on a clean layout, minimal color schemes, and easy-to-read fonts. Use whitespace effectively to create a sense of balance and allow important elements to stand out. - -### Key aspects of simplicity include: - -1. **Colour:** Use a limited color palette that complements your brand and enhances readability. Avoid using too many colors that can distract users. - -2. **Type:** Choose fonts that are easy to read and reflect your brand's personality. Limit the number of different fonts to maintain a cohesive look. - -3. **Imagery:** Use high-quality images that are relevant to your content. Avoid cluttering the design with too many visuals, and ensure that images are properly sized and optimized for fast loading. - -4. **Content:** Keep text concise and to the point. Use headings, bullet points, and short paragraphs to make content easy to scan. - - -## 3. Navigation - -Effective navigation is essential for helping users find their way around your website. A well-structured navigation menu should be intuitive and easy to use, allowing visitors to quickly access the information they need. - -### Tips for effective navigation: - -- **Consistent Layout:** Keep the navigation menu in a consistent location across all pages, typically at the top or side of the page. -- **Clear Labels:** Use clear and descriptive labels for menu items to help users understand where they will be taken. -- **Logical Structure:** Organize menu items in a logical hierarchy, grouping related items together. -- **Responsive Design:** Ensure that the navigation menu is easy to use on both desktop and mobile devices. - -## 4. F-shaped Pattern - -Users often scan web pages in an F-shaped pattern, focusing on the top and left side of the page. To accommodate this behavior, place important elements such as headlines, calls to action, and key information in these areas. This helps ensure that users see the most critical content first. - -## 5. Visual Hierarchy - -Visual hierarchy refers to the arrangement of elements on a page in a way that indicates their importance. By using size, color, contrast, and spacing, you can guide users' attention to the most important parts of your website. - -### Techniques for creating visual hierarchy: - -- **Size:** Larger elements tend to draw more attention. Use larger fonts for headings and important information. -- **Color:** Use contrasting colors to highlight key elements, such as calls to action. -- **Spacing:** Use whitespace to separate different sections and create a clear structure. -- **Alignment:** Align elements consistently to create a clean and organized look. -- **Repetition:** Use consistent styles for similar elements to create a cohesive design. - -## 6. Content - -Content is a critical component of web design. High-quality, relevant content not only attracts visitors but also keeps them engaged. Ensure that your content is well-written, informative, and aligned with your website's purpose. - -### Tips for effective content: - -- **Clarity:** Write in a clear and concise manner, avoiding jargon or complex language. -- **Relevance:** Ensure that content is relevant to your target audience and addresses their needs or interests. -- **Engagement:** Use engaging headlines, subheadings, and visuals to capture users' attention. -- **SEO:** Optimize content for search engines to improve visibility and attract organic traffic. -- **Regular Updates:** Keep content fresh and up-to-date to encourage repeat visits. - -## 7. Grid-Based Layouts - -Using a grid-based layout helps create a structured and organized design. Grids provide a framework for aligning elements, ensuring consistency and balance across the website. This approach makes it easier to create a visually appealing design that is easy to navigate. - -### Benefits of grid-based layouts: - -- **Consistency:** Grids help maintain a consistent layout across different pages and sections of the website. -- **Alignment:** Grids provide a guide for aligning elements, creating a clean and organized look. -- **Flexibility:** Grids can be adapted to different screen sizes and devices, making them ideal for responsive design. -- **Efficiency:** Using a grid system can speed up the design process by providing a clear structure to work within. -- **Visual Appeal:** A well-structured grid layout can enhance the overall aesthetic of the website, making it more visually appealing to users. -- **User Experience:** A grid-based layout can improve the user experience by making it easier for users to find and interact with content. -- **Professionalism:** A grid-based design often appears more polished and professional, which can enhance the credibility of the website. - -## 8. Loading Time - -Website loading time is a critical factor in user experience. Slow-loading websites can frustrate users and lead to higher bounce rates. Optimize your website's performance by minimizing file sizes, using efficient coding practices, and leveraging caching techniques. - -### Tips for improving loading time: - -- **Optimize Images:** Compress images without sacrificing quality to reduce file sizes. -- **Minimize Code:** Remove unnecessary code and use minification techniques to reduce file sizes. -- **Use Caching:** Implement browser caching to store frequently accessed files locally on users' devices. -- **Content Delivery Network (CDN):** Use a CDN to distribute content across multiple servers -- **Limit Plugins:** Avoid using too many plugins, as they can slow down your website. -- **Choose a Reliable Hosting Provider:** Select a hosting provider that offers fast and reliable performance. -- **Monitor Performance:** Regularly test your website's loading time using tools like Google PageSpeed Insights or GTmetrix and make necessary improvements. - - -## 9. Mobile-Friendly Design - -With the increasing use of mobile devices to access the internet, having a mobile-friendly design is essential. A responsive design ensures that your website looks and functions well on all screen sizes, providing a seamless experience for users regardless of the device they are using. - -### Tips for creating a mobile-friendly design: - -- **Responsive Layout:** Use flexible grids and layouts that adapt to different screen sizes. -- **Touch-Friendly Elements:** Ensure that buttons and links are large enough to be easily tapped on a touchscreen. -- **Simplified Navigation:** Use a simplified navigation menu that is easy to use on smaller screens. -- **Optimized Content:** Ensure that content is easy to read on mobile devices, using larger fonts and shorter paragraphs. -- **Fast Loading:** Optimize your website for fast loading on mobile networks, which may be slower than desktop connections. -- **Test on Multiple Devices:** Regularly test your website on various mobile devices to ensure compatibility and a consistent user experience. - -By following these nine principles of good web design, you can create a website that is visually appealing, user-friendly, and effective in achieving its purpose. Remember to continuously evaluate and improve your design based on user feedback and changing trends in web design. - -## Conclusion - -Good web design is a combination of aesthetics, functionality, and user experience. By adhering to these nine principles, you can create a website that not only looks great but also provides value to your visitors. Whether you're building a new website or redesigning an existing one, keep these principles in mind to ensure your site stands out and meets the needs of your audience. \ No newline at end of file diff --git a/blog/authors.yml b/blog/authors.yml deleted file mode 100644 index bb45a813f..000000000 --- a/blog/authors.yml +++ /dev/null @@ -1,19 +0,0 @@ -ajay-dhangar: - name: Ajay Dhangar - title: Founder of CodeHarborHub - url: https://ajay-dhangar.github.io/ - image_url: https://avatars.githubusercontent.com/u/99037494?v=4 - email: ajaydhangar49@gmail.com - page: true # Turns the feature on - description: > - A passionate developer who loves to code and build new things. I am a Full Stack Developer and a Cyber Security, ML & AI Enthusiast. I am also a Technical Content Writer and a Speaker. I love to share my knowledge with the community. I am the Founder of CodeHarborHub. I am also a Technical Content Writer at GeeksforGeeks. I am a Girl Script Summer of Code 2024 Project Manager (PA). - - socials: - x: CodesWithAjay - linkedin: ajay-dhangar - github: ajay-dhangar - stackoverflow: 18530900 - instagram: _ajay.dhangar - newsletter: https://ajay-dhangar.github.io - bluesky: ajay-dhangar.bsky.social - youtube: ajay-dhangar \ No newline at end of file diff --git a/blog/introduction-to-cryptography-and-cyber-security.md b/blog/introduction-to-cryptography-and-cyber-security.md deleted file mode 100644 index 1abf88422..000000000 --- a/blog/introduction-to-cryptography-and-cyber-security.md +++ /dev/null @@ -1,85 +0,0 @@ ---- -slug: cryptography-and-cyber-security -title: Cryptography and Its Use in Cyber Security -sidebar_label: Cryptography and Cyber Security -image: /img/codeharborhub-social-card.jpg -authors: [ajay-dhangar] -tags: [cryptography, cyber-security, encryption] -date: 2024-06-24 -# hide_table_of_contents: true ---- - -In the realm of cyber security, cryptography stands as a critical tool for protecting information. As digital data exchange grows exponentially, the importance of cryptography in ensuring data security and privacy cannot be overstated. This blog explores the fundamental concepts of cryptography, its historical significance, and its contemporary applications in cyber security. - - - -## Understanding Cryptography - -Cryptography is the science of encoding and decoding information to protect it from unauthorized access. It involves various techniques and algorithms that transform readable data, known as plaintext, into an unreadable format, known as ciphertext. Only those who possess the appropriate decryption key can convert the ciphertext back into plaintext. - -### Key Concepts in Cryptography - -1. **Encryption and Decryption**: The process of converting plaintext into ciphertext is called encryption, while the process of converting ciphertext back into plaintext is called decryption. -2. **Symmetric Key Cryptography**: The same key is used for both encryption and decryption. Examples include AES and DES. -3. **Asymmetric Key Cryptography**: Uses a pair of keys - a public key for encryption and a private key for decryption. Examples include RSA and ECC. -4. **Hash Functions**: Take an input and produce a fixed-size string of characters, which is typically a hash value. Hash functions are used for data integrity and password storage. - -## Historical Significance of Cryptography - -Cryptography has been used for centuries to secure communication. Some historical milestones include: - -- **Caesar Cipher**: Used by Julius Caesar to protect military messages, this substitution cipher shifts letters by a fixed number of positions in the alphabet. -- **Enigma Machine**: Used by the Germans during World War II, this electromechanical device encrypted messages. The successful decryption of Enigma-encrypted messages by the Allies significantly impacted the war's outcome. -- **Diffie-Hellman Key Exchange**: Introduced in 1976, this method allowed secure key exchange over a public channel, laying the groundwork for modern public-key cryptography. - -## Cryptography in Modern Cyber Security - -In today's digital world, cryptography is essential for securing data and maintaining privacy. Its applications are vast and varied: - -### Secure Communication - -Cryptography ensures that communication between parties remains confidential and secure. Protocols like SSL/TLS use cryptographic techniques to protect data transmitted over the internet, such as during online banking and shopping. - -### Data Integrity - -Hash functions play a crucial role in ensuring data integrity. When data is transmitted or stored, hash functions can verify that the data has not been altered. This is particularly important for software distribution and digital signatures. - -### Authentication - -Cryptographic methods are used to verify the identities of users and devices. Passwords are typically stored as hash values, and public-key infrastructure (PKI) systems use digital certificates to authenticate entities. - -### Blockchain Technology - -Cryptography is the backbone of blockchain technology. Cryptographic hashing ensures the integrity of data blocks, while asymmetric cryptography secures transactions and verifies identities. This technology underpins cryptocurrencies like Bitcoin and has applications in various fields, including supply chain management and healthcare. - -### Secure Storage - -Encrypting data at rest ensures that even if unauthorized individuals gain access to storage media, they cannot read the data without the decryption key. This is crucial for protecting sensitive information on devices and in cloud storage. - -## Challenges in Cryptography - -While cryptography is a powerful tool, it is not without challenges: - -- **Key Management**: Securely generating, storing, and distributing cryptographic keys is complex and critical for maintaining security. -- **Performance Overheads**: Cryptographic operations can be computationally intensive, affecting system performance, especially in resource-constrained environments. -- **Quantum Computing**: Emerging quantum computers have the potential to break many of the cryptographic algorithms currently in use, necessitating the development of quantum-resistant algorithms. - -## Future Directions in Cryptography - -The field of cryptography is continuously evolving to address emerging threats and challenges. Some future directions include: - -### Post-Quantum Cryptography - -With the advent of quantum computing, researchers are developing cryptographic algorithms that are resistant to quantum attacks. These algorithms aim to provide security even in the presence of powerful quantum computers. - -### Homomorphic Encryption - -This advanced form of encryption allows computations to be performed on encrypted data without decrypting it. Homomorphic encryption has significant implications for data privacy, particularly in cloud computing and data analysis. - -### Zero-Knowledge Proofs - -Zero-knowledge proofs enable one party to prove to another that a statement is true without revealing any information beyond the validity of the statement. This concept has applications in authentication, privacy-preserving protocols, and blockchain technology. - -## Conclusion - -Cryptography is a cornerstone of cyber security, providing the means to protect data and maintain privacy in an increasingly interconnected world. As technology advances and new threats emerge, the field of cryptography will continue to evolve, offering innovative solutions to ensure the security and integrity of our digital lives. By understanding and implementing cryptographic techniques, individuals and organizations can safeguard their information and build a secure future. diff --git a/blog/introduction-to-the-Linux-development-and-cyber-security.md b/blog/introduction-to-the-Linux-development-and-cyber-security.md deleted file mode 100644 index 7b0821a57..000000000 --- a/blog/introduction-to-the-Linux-development-and-cyber-security.md +++ /dev/null @@ -1,78 +0,0 @@ ---- -slug: linux-development-and-cyber-security -title: Comprehensive Documentation on Linux Development and Cybersecurity -sidebar_label: Linux development and cyber security -image: /img/codeharborhub-social-card.jpg -authors: [ajay-dhangar] -tags: [cyber-security, linux, internet, technology] -date: 2024-06-23 -# hide_table_of_contents: false ---- - -Linux, renowned for its stability, security, and open-source nature, plays a pivotal role in modern computing environments, particularly in development and cybersecurity. This documentation explores how Linux facilitates software development processes and serves as a secure foundation for cybersecurity operations. - - - -## Linux in Development - -### Open Source Ecosystem - -Linux's open-source ecosystem fosters collaboration and innovation among developers globally. The availability of source code, community-driven development, and licensing freedoms enable developers to customize, extend, and redistribute software. Popular Linux distributions (distros) like Ubuntu, Debian, and CentOS provide comprehensive repositories of software packages, enhancing productivity and scalability in development workflows. - -### Command-Line Tools and Scripting - -Linux excels in its command-line interface (CLI) capabilities, offering a plethora of command-line tools essential for software development. Tools like `grep`, `sed`, `awk`, and `find` facilitate text processing, pattern matching, and file manipulation tasks. The CLI's scripting capabilities empower developers to automate repetitive tasks, configure system settings, and deploy applications consistently across environments, promoting efficiency and reproducibility. - -### Integrated Development Environments (IDEs) - -Linux supports a variety of Integrated Development Environments (IDEs) tailored to different programming languages and workflows. IDEs like `Eclipse`, `Visual Studio Code`, and `IntelliJ IDEA` provide robust features such as code debugging, version control integration, and syntax highlighting. These tools streamline development processes, improve code quality, and enhance collaboration among team members, making Linux a preferred choice for software development projects of all scales. - -### Package Management and Dependency Resolution - -Linux distributions incorporate advanced package management systems like `dpkg` (Debian Package Manager), `rpm` (Red Hat Package Manager), and package repositories (`apt`, `yum`, `snap`) to streamline software installation, updates, and dependency resolution. Package managers ensure software integrity, manage library dependencies, and facilitate seamless integration of third-party libraries and frameworks into development projects, fostering innovation and interoperability. - -### Version Control Systems (VCS) - -Version Control Systems (VCS) like `Git`, `Subversion (SVN)`, and `Mercurial` are integral to collaborative software development on Linux. VCS platforms enable developers to track changes, manage project versions, and facilitate code review processes. `Git`, in particular, with platforms like `GitHub` and `GitLab`, empowers distributed development teams to collaborate effectively, share code repositories, and leverage community-driven development practices, promoting transparency and code quality assurance. - -### Containerization and Virtualization - -Linux is instrumental in containerization and virtualization technologies, enabling efficient resource utilization, application deployment, and scalability. Container orchestration platforms like `Docker`, `Kubernetes`, and `LXC/LXD` leverage Linux's lightweight container support (`cgroups`, `namespaces`) to isolate applications, streamline deployment workflows, and manage complex microservices architectures. Virtualization solutions (`KVM`, `VirtualBox`) on Linux provide virtual machine (VM) management, hardware virtualization, and sandboxing capabilities, facilitating development and testing in isolated environments. - -### Performance Monitoring and Optimization - -Linux offers robust tools (`top`, `htop`, `vmstat`) and performance monitoring utilities (`sar`, `perf`) to analyze system performance metrics, monitor resource utilization, and diagnose bottlenecks. Performance tuning techniques, such as kernel parameter adjustments (`sysctl`), filesystem optimization (`ext4`, `XFS`), and memory management (`swappiness`, `oom-killer`), enhance application responsiveness, scalability, and reliability on Linux-based infrastructures, ensuring optimal performance under varying workloads. - -### Cloud Computing and DevOps - -Linux's compatibility with cloud computing platforms (`AWS`, `Google Cloud`, `Azure`) and DevOps tools (`Ansible`, `Chef`, `Puppet`) supports agile development practices, infrastructure automation, and continuous integration/continuous delivery (CI/CD) pipelines. Linux-based server configurations (`nginx`, `Apache`) facilitate web hosting, load balancing, and scalable application deployments, empowering organizations to deploy resilient, scalable, and cost-effective solutions in cloud environments. - -## Linux in Cybersecurity - -### Security Architecture and Mechanisms - -Linux's security architecture encompasses robust mechanisms designed to mitigate security risks and protect system integrity. Key security features include: - -- **Access Control:** Linux employs discretionary access control (DAC) and mandatory access control (MAC) mechanisms to enforce file permissions and restrict unauthorized access based on user roles and privileges. -- **Security-Enhanced Linux (SELinux):** SELinux enhances system security by implementing mandatory access controls (MAC) through policy enforcement, sandboxing processes, and limiting potential exploits. -- **Kernel Hardening:** Regular kernel updates, security patches, and proactive security measures harden Linux against vulnerabilities, ensuring system resilience and mitigating potential threats. - -### Penetration Testing and Vulnerability Assessment - -Linux serves as a pivotal platform for penetration testing, vulnerability assessment, and digital forensics in cybersecurity operations. Tools like `Metasploit`, `Nmap`, `Wireshark`, and `Burp Suite` enable cybersecurity professionals to assess network security, identify vulnerabilities, and simulate real-world attack scenarios. These tools facilitate proactive threat detection, incident response planning, and security posture assessment, ensuring robust defense against cyber threats and malicious activities. - -### Incident Response and Forensics - -Linux serves as a robust platform for incident response (IR) and digital forensics investigations, offering tools (`Autopsy`, `The Sleuth Kit`, `Volatility`) and methodologies to analyze digital evidence, recover compromised systems, and attribute security incidents. IR frameworks (`CIRCL`, `MISP`) and threat intelligence platforms (`OpenCTI`, `STIX/TAXII`) leverage Linux's interoperability and scalability to coordinate incident response efforts, share threat intelligence, and mitigate cyber threats effectively. - -### Network Security and Monitoring - -Linux-based network security tools (`Snort`, `Suricata`, `Bro/Zeek`) monitor network traffic, detect intrusions, and analyze security events in real-time. Network monitoring solutions (`Nagios`, `Zabbix`, `Prometheus`) provide visibility into system performance, network availability, and service uptime, ensuring proactive threat detection, anomaly detection, and compliance with regulatory requirements (`GDPR`, `PCI DSS`) in diverse network environments. - -### Secure Configuration and Hardening - -Linux administrators implement secure configuration baselines (`CIS Benchmarks`, `STIGs`) and hardening guidelines (`Securing Debian Manual`, `Red Hat Hardening Guide`) to mitigate security risks, enforce security policies, and safeguard critical assets. Security automation tools (`Ansible`, `SaltStack`, `Chef`) automate configuration management, enforce compliance checks, and remediate vulnerabilities across Linux-based infrastructures, promoting consistent security posture and resilience against evolving cyber threats. - -## Conclusion - -Linux's pervasive adoption in software development and cybersecurity underscores its indispensable role as a versatile, scalable, and secure platform. By harnessing Linux's robust development tools, comprehensive security features, and ecosystem support, organizations empower developers and cybersecurity professionals to innovate, collaborate, and defend against emerging threats effectively. Embracing Linux as a foundational technology fosters agility, scalability, and resilience in adapting to dynamic business requirements and addressing evolving cybersecurity challenges in the digital age. diff --git a/blog/introduction-to-web-assembly.md b/blog/introduction-to-web-assembly.md deleted file mode 100644 index 0ba26d098..000000000 --- a/blog/introduction-to-web-assembly.md +++ /dev/null @@ -1,89 +0,0 @@ ---- -slug: introduction-to-web-assembly -title: Introduction to WebAssembly -sidebar_label: WebAssembly and Web Performance -image: /img/codeharborhub-social-card.jpg -authors: [ajay-dhangar] -tags: [webassembly, wasm, web-performance] -date: 2024-07-21 -# hide_table_of_contents: true ---- - -WebAssembly (Wasm) is a binary instruction format that provides near-native performance for web applications. Designed as a portable compilation target for high-level languages like C, C++, and Rust, WebAssembly enables efficient execution of code on modern web browsers. This documentation introduces WebAssembly, its benefits, and how to get started with Wasm development. - - - -## What is WebAssembly (Wasm)? - -WebAssembly is a low-level, assembly-like language with a compact binary format that runs with near-native performance. It provides a new way to run code written in multiple languages on the web at near-native speed, allowing for powerful web applications. - -## Why Use WebAssembly? - -WebAssembly offers several advantages: - -- **Performance:** Wasm code executes at near-native speeds, making it ideal for performance-critical applications like games, simulations, and complex calculations. -- **Portability:** Code compiled to Wasm can run on any modern web browser, providing a consistent execution environment across different platforms. -- **Interoperability:** Wasm integrates seamlessly with JavaScript, enabling the use of existing web technologies and frameworks. -- **Security:** Wasm operates in a safe, sandboxed execution environment, reducing the risk of security vulnerabilities. - -## How WebAssembly Works - -WebAssembly works by compiling high-level code into a binary format that can be executed by the browser's virtual machine. The process involves several steps: - -1. **Source Code:** Write your code in a high-level language like C, C++, or Rust. -2. **Compilation:** Use a compiler to convert the source code into WebAssembly binary format (`.wasm` file). -3. **Execution:** The browser's virtual machine executes the Wasm binary, providing near-native performance. - -## Setting Up Your Environment - -To start developing with WebAssembly, you'll need to set up your development environment. This includes installing the necessary tools and compilers. - -### Setting Up a Development Environment - -1. **Install Node.js:** Node.js is required for various Wasm development tools. -2. **Install a Compiler:** Depending on your source language, install a suitable compiler. For C/C++, install Emscripten. For Rust, install the Rust toolchain. - -### Compiling to WebAssembly - -To compile your code to WebAssembly, follow these steps: - -1. **Write Your Code:** Write your application in C, C++, Rust, or another supported language. -2. **Compile:** Use your compiler to generate the Wasm binary. For example, with Emscripten, use the following command: - ```bash - emcc your_code.c -o your_code.wasm - ``` - For Rust: - -``` -rustc --target wasm32-unknown-unknown -O your_code.rs -``` - -## Interfacing with JavaScript - -WebAssembly can interact with JavaScript, enabling you to call Wasm functions from JavaScript and vice versa. Use the JavaScript WebAssembly API to load and instantiate Wasm modules. - -## Debugging WebAssembly Code - -Debugging Wasm code involves using browser developer tools and other utilities: - -- Browser DevTools: Modern browsers provide debugging support for WebAssembly, including breakpoints, step execution, and variable inspection. -- Source Maps: Generate source maps to map Wasm code back to the original source code for easier debugging. -- Optimizing WebAssembly Performance - -To optimize Wasm performance: - -- Optimize Code: Write efficient, performance-oriented code in the source language. -- Compiler Flags: Use compiler optimization flags to improve the performance of the generated Wasm binary. -- Profiling: Use profiling tools to identify and address performance bottlenecks. - -## Case Studies and Real-World Examples - -Explore case studies and real-world examples of WebAssembly in action: - -- Gaming: High-performance games running in the browser. -- Data Visualization: Complex data visualizations with real-time interactivity. -- Scientific Simulations: Web-based simulations for scientific research and education. - -## Conclusion - -WebAssembly is a powerful technology that enhances web performance and expands the capabilities of web applications. By leveraging Wasm, developers can build high-performance, portable, and secure applications that run seamlessly across different browsers and platforms. This documentation provides a comprehensive guide to getting started with WebAssembly, covering essential concepts, tools, and best practices. diff --git a/blog/microservices-architecture.md b/blog/microservices-architecture.md deleted file mode 100644 index b69f72598..000000000 --- a/blog/microservices-architecture.md +++ /dev/null @@ -1,190 +0,0 @@ ---- -slug: microservices-architecture -title: "Microservices Architecture" -sidebar_label: Microservices Basics -image: /img/codeharborhub-social-card.jpg -authors: [ajay-dhangar] -tags: [microservices, architecture] -date: 2024-07-29 -# hide_table_of_contents: true ---- - -Microservices architecture is an approach to designing software systems where the application is broken down into smaller, loosely coupled, and independently deployable services. Each service focuses on a specific business functionality and communicates with other services through well-defined APIs. This architecture enables easier maintenance, scalability, and faster deployment cycles. - - - -## Designing Microservices Architecture - -Designing a microservices architecture involves: - -- **Service Decomposition:** Identifying and defining the boundaries of individual services based on business capabilities. -- **Data Management:** Deciding on the data storage approach, whether to use a shared database or a database per service. -- **Communication:** Choosing the communication mechanism (REST, gRPC, messaging) between services. -- **Service Discovery:** Implementing a way for services to find each other dynamically. -- **API Gateway:** Providing a single entry point for clients to interact with multiple services. - -## Tools and Frameworks - -Several tools and frameworks are essential for developing and managing microservices: - -- **Spring Boot:** A Java-based framework for building microservices with ease. -- **Docker:** A platform for containerizing applications, making them portable and consistent across environments. -- **Kubernetes:** An orchestration tool for managing containerized applications at scale. - -### Example: Creating a Simple Microservice with Spring Boot - -```java -@RestController -@RequestMapping("/api") -public class ExampleController { - - @GetMapping("/hello") - public String sayHello() { - return "Hello from Microservice!"; - } -} -``` - -### Example: Dockerizing a Spring Boot Application - -```dockerfile -# Use an official OpenJDK runtime as a parent image -FROM openjdk:11-jre-slim - -# Set the working directory -WORKDIR /app - -# Copy the application JAR file into the container -COPY target/myapp.jar /app/myapp.jar - -# Run the application -ENTRYPOINT ["java", "-jar", "myapp.jar"] -``` - -### Example: Deploying to Kubernetes - -```yaml -apiVersion: apps/v1 -kind: Deployment -metadata: - name: myapp-deployment -spec: - replicas: 3 - selector: - matchLabels: - app: myapp - template: - metadata: - labels: - app: myapp - spec: - containers: - - name: myapp - image: myapp:latest - ports: - - containerPort: 8080 -``` - -## Monitoring and Managing Microservices - -Effective monitoring and management are crucial for microservices: - -- **Logging:** Centralized logging solutions like ELK Stack (Elasticsearch, Logstash, Kibana). -- **Metrics:** Monitoring system performance with Prometheus and Grafana. -- **Tracing:** Distributed tracing tools like Jaeger or Zipkin for tracking requests across services. - -### Example: Setting Up Prometheus and Grafana - -```yaml -# Prometheus Deployment -apiVersion: apps/v1 -kind: Deployment -metadata: - name: prometheus-deployment -spec: - replicas: 1 - selector: - matchLabels: - app: prometheus - template: - metadata: - labels: - app: prometheus - spec: - containers: - - name: prometheus - image: prom/prometheus - ports: - - containerPort: 9090 -# Grafana Deployment -apiVersion: apps/v1 -kind: Deployment -metadata: - name: grafana-deployment -spec: - replicas: 1 - selector: - matchLabels: - app: grafana - template: - metadata: - labels: - app: grafana - spec: - containers: - - name: grafana - image: grafana/grafana - ports: - - containerPort: 3000 -``` - -## Real-World Examples and Performance Considerations - -### Choosing the Right Tools and Frameworks - -Selecting the appropriate tools and frameworks depends on factors like: - -- **Language Preferences:** Spring Boot for Java, Flask for Python, Express for Node.js. -- **Containerization Needs:** Docker for creating consistent environments. -- **Orchestration Requirements:** Kubernetes for managing containerized applications. - -### Monitoring and Managing Microservices - -To ensure reliability and performance: - -- **Health Checks:** Regularly check the health of services using Kubernetes liveness and readiness probes. -- **Autoscaling:** Automatically scale services based on load using Kubernetes Horizontal Pod Autoscaler. -- **Circuit Breakers:** Implement fault tolerance with tools like Hystrix. - -### Real-World Examples - -Several companies have successfully implemented microservices: - -- **Netflix:** Uses microservices to handle massive traffic and deliver streaming content. -- **Amazon:** Migrated from a monolithic architecture to microservices to improve scalability and resilience. - -They have faced challenges such as: - -- **Complexity:** Managing numerous services can be complex. -- **Data Consistency:** Ensuring consistency across distributed services. - -### Performance Considerations - -Scaling microservices involves: - -- **Load Balancing:** Distributing traffic evenly across services using tools like NGINX or Kubernetes Ingress. -- **Caching:** Reducing load on services by caching responses with tools like Redis or Memcached. -- **Optimizing Database Access:** Using techniques like connection pooling and query optimization. -- **Start Small:** Begin with a single microservice and gradually refactor other parts of your application. -- **Use Best Practices:** Follow industry best practices for design, implementation, and monitoring. -- **Continuously Improve:** Regularly review and optimize your microservices architecture. - -## Conclusion - -Microservices architecture offers significant benefits in terms of scalability, maintainability, and agility. By leveraging tools like Spring Boot, Docker, and Kubernetes, and following best practices for design, monitoring, and management, you can build robust and efficient microservices-based systems. - -For further learning: - -- **Books:** "Building Microservices" by Sam Newman, "Microservices Patterns" by Chris Richardson. -- **Online Courses:** Udemy, Coursera, and Pluralsight offer courses on microservices. -- **Communities:** Join microservices communities and forums to connect with other practitioners. diff --git a/blog/quantum-computing-and-its-application.md b/blog/quantum-computing-and-its-application.md deleted file mode 100644 index 498d3627e..000000000 --- a/blog/quantum-computing-and-its-application.md +++ /dev/null @@ -1,107 +0,0 @@ ---- -slug: quantum-computing-and-its-application -title: Introduction to Quantum Computing -sidebar_label: Quantum Computing -image: /img/codeharborhub-social-card.jpg -authors: [ajay-dhangar] -tags: [quantum, applications, computing] -keywords: [quantum, applications, computing] -description: An introductory blog post about quantum computing, its basic concepts, and potential applications in various fields. -date: 2024-11-25 ---- - -In the realm of computing, quantum computing stands as a revolutionary field that leverages the principles of quantum mechanics to process information in fundamentally different ways compared to classical computing. This blog aims to introduce the basics of quantum computing, explore its potential applications, and provide resources for further learning. - - - -## Quantum Computing: Basics and Applications - -Quantum computing is a revolutionary field that leverages the principles of quantum mechanics to process information in fundamentally different ways compared to classical computing. This blog will introduce the basics of quantum computing, explore its potential applications, and provide resources for further learning. - -## Introduction to Quantum Computing - -Quantum computing harnesses the peculiar principles of quantum mechanics, such as superposition and entanglement, to perform computations that would be infeasible for classical computers. While classical computers use bits as the smallest unit of information (which can be 0 or 1), quantum computers use quantum bits, or qubits, which can represent both 0 and 1 simultaneously due to superposition. - -## Basic Concepts - -### Quantum Bits (Qubits) - -A qubit is the fundamental unit of quantum information. Unlike a classical bit, which can be either 0 or 1, a qubit can exist in a state that is a linear combination of both. This property is called superposition. Mathematically, a qubit's state can be represented as: - -$$ -|\psi\rangle = \alpha|0\rangle + \beta|1\rangle -$$ - -where $|\alpha|^2$ and $|\beta|^2$ are the probabilities of the qubit being in the state $|0\rangle$ and $|1\rangle$ respectively, and $|\alpha|^2 + |\beta|^2 = 1$. - -### Superposition - -Superposition is the ability of a quantum system to be in multiple states simultaneously. For qubits, this means they can represent both 0 and 1 at the same time. This property enables quantum computers to process a vast amount of possibilities simultaneously, providing an exponential speed-up for certain computations. - -### Entanglement - -Entanglement is a quantum phenomenon where two or more qubits become correlated in such a way that the state of one qubit instantly influences the state of the other, regardless of the distance between them. This correlation is a key resource for quantum computing, enabling complex operations and secure communication protocols. - -### Quantum Gates - -Quantum gates are the building blocks of quantum circuits, analogous to classical logic gates. They manipulate qubits through unitary transformations. Some fundamental quantum gates include: - -- **Pauli-X Gate**: Flips the state of a qubit, analogous to a NOT gate in classical computing. -- **Hadamard Gate**: Creates superposition, transforming a qubit from the state. -- **CNOT Gate**: A two-qubit gate that flips the second qubit if the first qubit is in the state. - -## Applications of Quantum Computing - -### Cryptography - -Quantum computing poses a significant threat to classical cryptographic systems. Algorithms like Shor's algorithm can factor large numbers exponentially faster than the best-known classical algorithms, potentially breaking widely used encryption methods such as RSA. On the flip side, quantum cryptography offers new ways to secure information, such as Quantum Key Distribution (QKD), which guarantees secure communication based on the principles of quantum mechanics. - -### Optimization Problems - -Many real-world problems, such as supply chain management, financial modelling, and route optimization, involve finding the best solution among a vast number of possibilities. Quantum computing can provide significant speed-ups for solving these optimization problems using algorithms like the Quantum Approximate Optimization Algorithm (QAOA) and Grover's algorithm. - -### Drug Discovery - -Quantum computers can simulate molecular interactions at a quantum level, providing insights into the behavior of complex molecules. This capability is crucial for drug discovery and materials science, as it allows researchers to model and predict chemical reactions more accurately, potentially leading to the development of new medications and materials. - -### Machine Learning - -Quantum machine learning combines quantum computing and classical machine learning techniques to enhance data processing capabilities. Quantum computers can process large datasets and complex models more efficiently, leading to faster training times and improved performance for certain machine learning tasks. - -## Resources for Further Learning - -### Books - -1. **"Quantum Computing: A Gentle Introduction" by Eleanor Rieffel and Wolfgang Polak** - - - A comprehensive introduction to the principles and applications of quantum computing. - -2. **"Quantum Computation and Quantum Information" by Michael A. Nielsen and Isaac L. Chuang** - - Often considered the definitive textbook on quantum computing, covering a wide range of topics in depth. - -### Papers - -1. **"Simulating Physics with Computers" by Richard Feynman** - - - One of the foundational papers in quantum computing, introducing the concept of using quantum systems for simulation. - -2. **"Shor's Algorithm for Quantum Factoring" by Peter Shor** - - The seminal paper that introduced Shor's algorithm, demonstrating the potential of quantum computers to solve certain problems exponentially faster than classical computers. - -### Online Courses - -1. **"Quantum Computing for the Very Curious" by Michael Nielsen** - - - A free, interactive online book that provides a hands-on introduction to quantum computing. - -2. **Coursera: "Quantum Computing" by University of Toronto** - - A comprehensive course covering the basics of quantum computing, quantum algorithms, and quantum hardware. - -### Tutorials and Blogs - -1. **Qiskit Tutorials** - - IBM's open-source quantum computing framework provides extensive tutorials and resources for learning quantum programming. -2. **Quantum Computing Report** - - A blog that keeps up with the latest news, developments, and insights in the field of quantum computing. - -By understanding these basic concepts and exploring the resources provided, you can build a strong foundation in quantum computing and appreciate its potential to revolutionize various industries. diff --git a/blog/react-js.md b/blog/react-js.md deleted file mode 100644 index 4e1161004..000000000 --- a/blog/react-js.md +++ /dev/null @@ -1,238 +0,0 @@ ---- -slug: react-js -title: "React JS" -sidebar_label: React JS -authors: [ajay-dhangar] -tags: [js, react-js, node-js] -date: 2024-06-13 -# hide_table_of_contents: true -image: /img/codeharborhub-social-card.jpg ---- - -React is a JavaScript library primarily used for building user interfaces in single-page applications. While it's often integrated with tools like Webpack for bundling JavaScript and CSS files, React itself does not directly incorporate Webpack. Despite its nature as a library rather than a full framework or programming language, React remains instrumental in modern web development. - - - -React offers various extensions for entire application architectural support, such as Flux and React Native, beyond mere UI. - -## Why React? - -- Declarative Nature: React's declarative approach allows developers to describe the desired UI state, and React handles the rendering efficiently. This simplifies the development process by abstracting away the manual DOM manipulation. - -- Improved Performance: React uses Virtual DOM, a lightweight representation of the actual DOM. By comparing the previous and current states of this Virtual DOM, React determines the minimal set of DOM operations needed to update the UI, resulting in faster rendering and better performance. - -- Unidirectional Data Flow: In React, data flows in a unidirectional manner, typically from parent to child components. This ensures that any change in the parent component automatically propagates to its child components, simplifying the understanding of data changes and making it easier to trace errors. - -- Reusable Components: React promotes the creation of reusable UI components. Each component encapsulates its own logic and UI, allowing developers to compose complex UIs from simpler components. This modularity not only improves code organization but also accelerates development time. - -- Versatility: React's versatility extends beyond web development to mobile app development with React Native. This framework leverages React's component-based architecture to build native mobile apps using JavaScript and React principles. - -- Developer Tools: React is supported by dedicated developer tools like the React Developer Tools extension for Chrome. These tools facilitate debugging by providing insights into component hierarchies, state changes, and performance optimizations. - -## ReactJS History - -When compared to other technologies on the market, React is a new technology. React was created by Jordan Walke, a software engineer at Facebook, in 2011.Initially implemented in Facebook's News Feed, its success quickly led to its adoption in Instagram, showcasing its power and versatility in building dynamic user interfaces. - -## React Features - -Currently, ReactJS gaining quick popularity as the best JavaScript framework among web developers. It is playing an essential role in the front-end ecosystem. The important features of ReactJS are as following. - -![image](https://static.javatpoint.com/tutorial/reactjs/images/reactjs-features.png) - -### JSX - -JSX is a syntax extension for JavaScript that allows developers to write HTML-like code within JavaScript. This makes it easier to create and understand the structure of React components, as it closely resembles the final output in the browser. While not mandatory, using JSX is recommended in React development because it enhances readability and simplifies the creation of user interfaces. - -### Components - -React components enable reusability and encapsulation by breaking down UIs into self-contained pieces with their own structure, style, and behavior. This promotes code reuse, as components can be used across different parts of the application, enhancing maintainability and reducing bugs, while ensuring a clean separation of concerns. - -### One-way Data Binding - -One-way data binding is a pattern where data flows in a single direction, typically from the model to the view. This ensures that the state of an application is predictable and easier to manage. In the context of JavaScript frameworks, Flux and Redux are popular architectures that facilitate one-way data binding and state management. - -#### Flux - -Flux is an architecture pattern created by Facebook for building client-side web applications. It emphasizes unidirectional data flow and is composed of four key components: - -##### Action: - -- Actions are plain JavaScript objects or functions that contain the type of event and any associated data (payload). Actions are the only source of information for the store. - -##### Dispatcher: - -- The dispatcher is a central hub that manages all the data flow in a Flux application. When an action is created, it is dispatched to all stores that have registered with the dispatcher. The dispatcher’s role is to handle these actions and ensure they reach the appropriate store. - -##### Store: - -- Stores hold the application state and logic. They listen for actions from the dispatcher and update their state accordingly. Stores then emit a change event to notify the view layer to re-render. Each store manages a specific portion of the application's state. - -##### View: - -- The view is the presentation layer, typically composed of React components. Views listen to changes from the stores and re-render themselves accordingly. They can also generate new actions based on user interactions and send them to the dispatcher. - -### Virtual DOM - -A virtual DOM object is a representation of the original DOM object. It works like a one-way data binding. Whenever any modifications happen in the web application, the entire UI is re-rendered in virtual DOM representation. Then it checks the difference between the previous DOM representation and new DOM. Once it has done, the real DOM will update only the things that have actually changed. This makes the application faster, and there is no wastage of memory. - -### Simplicity - -ReactJS uses JSX file which makes the application simple and to code as well as understand. We know that ReactJS is a component-based approach which makes the code reusable as your need. This makes it simple to use and learn. - -### Performance - -ReactJS is known to be a great performer. This feature makes it much better than other frameworks out there today. The reason behind this is that it manages a virtual DOM. The DOM is a cross-platform and programming API which deals with HTML, XML or XHTML. The DOM exists entirely in memory. Due to this, when we create a component, we did not write directly to the DOM. Instead, we are writing virtual components that will turn into the DOM leading to smoother and faster performance. - -## React Ecosystem - -The React ecosystem is vast and diverse, encompassing a wide range of libraries and tools that enhance and extend the capabilities of React. These tools help in state management, routing, form handling, styling, and more, making React a robust framework for building complex and feature-rich applications. Here are some of the most popular libraries and tools commonly used with React: - -### State Management - -#### Redux - -Description: Redux is a state management library that provides a predictable state container for JavaScript apps. It helps manage application state and enables powerful debugging capabilities through tools like the Redux DevTools. - -Key Features: Centralized state, immutability, middleware support. - -#### MobX - -Description: MobX is a simple, scalable, and battle-tested state management solution. It uses observable data to efficiently react to state changes and update the UI. - -Key Features: Observable state, actions, reactions, computed values. - -#### Recoil - -Description: Recoil is a state management library for React developed by Facebook. It provides a set of utilities to manage state in a React application with minimal boilerplate. - -Key Features: Atoms, selectors, asynchronous state management. - -### Routing - -#### React Router - -Description: React Router is the most widely used routing library for React. It allows for dynamic routing in a web application, enabling navigation between different components and views. - -Key Features: Nested routes, dynamic routing, query parameters. - -### Form Handling - -#### Formik - -Description: Formik is a library that simplifies form management in React applications. It helps with form validation, error handling, and form submission. - -Key Features: Form state management, validation schema support, easy integration with validation libraries like Yup. - -#### React Hook Form - -Description: React Hook Form is a performant, flexible library for managing forms in React. It leverages React hooks for form state and validation, minimizing re-renders and improving performance. - -Key Features: Minimal re-renders, easy integration with UI libraries, built-in validation support. - -### Styling - -#### Styled Components - -Description: Styled Components is a library for styling React applications using tagged template literals. It allows for writing actual CSS to style components, keeping styles scoped and maintaining a clean component structure. - -Key Features: Scoped styling, theme support, dynamic styling. - -#### Emotion - -Description: Emotion is a flexible and powerful library for writing CSS styles with JavaScript. It provides both a styled component API and a CSS-in-JS approach. - -Key Features: Performant styles, server-side rendering, powerful theming capabilities. - -### Testing - -#### Jest - -Description: Jest is a JavaScript testing framework developed by Facebook, designed to ensure correctness of any JavaScript codebase. It works seamlessly with React, providing a simple and efficient way to test components and applications. - -Key Features: Snapshot testing, coverage reports, mocking capabilities. - -#### React Testing Library - -Description: React Testing Library is a testing utility that encourages testing best practices by focusing on user interactions and component behavior rather than implementation details. - -Key Features: Lightweight, integrates with Jest, emphasizes testing UI from the user’s perspective. - -### Build and Tooling - -#### Create React App - -Description: Create React App (CRA) is a CLI tool that sets up a new React project with a sensible default configuration. It handles configuration for tools like Webpack, Babel, ESLint, and more. - -Key Features: Zero configuration, fast setup, extensibility. - -#### Next.js - -Description: Next.js is a React framework that enables server-side rendering and static site generation for React applications. It simplifies the process of building complex React applications with features like API routes, file-based routing, and automatic code splitting. - -Key Features: Server-side rendering, static site generation, API routes, fast refresh. - -The React ecosystem is continuously evolving, with new tools and libraries emerging to address various needs and challenges in modern web development. These tools help streamline the development process, enhance performance, and ensure maintainability of React applications. - -## Pros and Cons of ReactJS - -Today, ReactJS is the highly used open-source JavaScript Library. It helps in creating impressive web apps that require minimal effort and coding. The main objective of ReactJS is to develop User Interfaces (UI) that improves the speed of the apps. There are important pros and cons of ReactJS given as following: - -Advantage of ReactJS - -### Easy to Learn and Use - -ReactJS is much easier to learn and use. It comes with a good supply of documentation, tutorials, and training resources. Any developer who comes from a JavaScript background can easily understand and start creating web apps using React in a few days. It is the V(view part) in the MVC (Model-View-Controller) model, and referred to as ?one of the JavaScript frameworks.? It is not fully featured but has the advantage of open-source JavaScript User Interface(UI) library, which helps to execute the task in a better manner. - -### Creating Dynamic Web Applications Becomes Easier - -#### JSX for Readability and Maintainability: - -- JSX (JavaScript XML) allows developers to write HTML elements in JavaScript. This mixture of HTML and JavaScript makes the code more readable and maintainable. For example, instead of splitting code between HTML and JavaScript files, JSX enables developers to write them together, making it easier to understand and work with the code. - -### Reusable Components - -A ReactJS web application is made up of multiple components, and each component has its own logic and controls. These components are responsible for outputting a small, reusable piece of HTML code which can be reused wherever you need them. The reusable code helps to make your apps easier to develop and maintain. These Components can be nested with other components to allow complex applications to be built of simple building blocks. ReactJS uses virtual DOM based mechanism to fill data in HTML DOM. The virtual DOM works fast as it only changes individual DOM elements instead of reloading complete DOM every time. - -### Performance Enhancement - -#### Virtual DOM vs. Real DOM: - -- React uses a virtual DOM to optimize updates and rendering. When the state of a component changes, React first updates the virtual DOM, a lightweight copy of the real DOM. It then compares this virtual DOM with a snapshot of the real DOM before applying only the necessary changes to the real DOM.Instead of re-rendering the entire DOM tree, React only updates the parts that have changed, which significantly boosts performance, especially in complex applications. - -### Known to be SEO Friendly - -Traditional JavaScript frameworks have an issue in dealing with SEO. The search engines generally having trouble in reading JavaScript-heavy applications. Many web developers have often complained about this problem. ReactJS overcomes this problem that helps developers to be easily navigated on various search engines. It is because React.js applications can run on the server, and the virtual DOM will be rendering and returning to the browser as a regular web page. - -### The Benefit of Having JavaScript Library - -Today, ReactJS is choosing by most of the web developers. It is because it is offering a very rich JavaScript library. The JavaScript library provides more flexibility to the web developers to choose the way they want. - -## Disadvantage of ReactJS - -### The high pace of development - -#### Continuous Learning and Updates: - -- The React ecosystem evolves rapidly, with frequent updates and new releases. While these updates bring improvements and new features, they also mean developers need to constantly learn and adapt. For example, React Hooks, introduced in version 16.8, brought a significant change in how state and side effects are handled. - -Developers had to quickly learn and integrate this new feature, which can be challenging and time-consuming. - -### Poor Documentation - -#### Rapid Updates Leading to Outdated Information: - -- While the official React documentation has improved, the rapid pace of updates can sometimes lead to outdated or incomplete information. For example, when new features like Concurrent Mode or Suspense are introduced, documentation might lag behind, making it difficult for developers to find accurate and up-to-date information. - -Developers might need to rely on community forums, blog posts, or other unofficial sources to fill in the gaps, which can be frustrating and time-consuming. - -### View Part - -ReactJS Covers only the UI Layers of the app and nothing else. So you still need to choose some other technologies to get a complete tooling set for development in the project. - -### JSX as a barrier - -ReactJS uses JSX. It's a syntax extension that allows HTML with JavaScript mixed together. This approach has its own benefits, but some members of the development community consider JSX as a barrier, especially for new developers. Developers complain about its complexity in the learning curve. - -### Official Documentation - -- https://react.dev/ diff --git a/blog/sql.md b/blog/sql.md deleted file mode 100644 index 738d1c5da..000000000 --- a/blog/sql.md +++ /dev/null @@ -1,142 +0,0 @@ ---- -slug: sql -title: SQL -image: https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTX6eSg-G0MWr9tVVTwAsVxWojlogGSx8pyBg&s -authors: [ajay-dhangar] -tags: [sql, database, mysql, nosql] -date: 2024-06-12 ---- - -Structured query language (SQL) is a programming language for storing and processing information in a relational database. A relational database stores information in tabular form, with rows and columns representing different data attributes and the various relationships between the data values. You can use SQL statements to store, update, remove, search, and retrieve information from the database. You can also use SQL to maintain and optimize database performance. - - - -## Why is SQL important? - -Structured query language (SQL) is a popular query language that is frequently used in all types of applications. Data analysts and developers learn and use SQL because it integrates well with different programming languages. For example, they can embed SQL queries with the Java programming language to build high-performing data processing applications with major SQL database systems such as Oracle or MS SQL Server. SQL is also fairly easy to learn as it uses common English keywords in its statements - -### History - -SQL was invented in the 1970s based on the relational data model. It was initially known as the structured English query language (SEQUEL). The term was later shortened to SQL. Oracle, formerly known as Relational Software, became the first vendor to offer a commercial SQL relational database management system. - -## Process of SQL - -When we are executing the command of SQL on any Relational database management system, then the system automatically finds the best routine to carry out our request, and the SQL engine determines how to interpret that particular command. - -Structured Query Language contains the following four components in its process: - -- Query Dispatcher -- Optimization Engines -- Classic Query Engine -- SQL Query Engine, etc. - -A classic query engine allows data professionals and users to maintain non-SQL queries. The architecture of SQL is shown in the following diagram: - -## What are the components of a SQL system? - -Relational database management systems use structured query language (SQL) to store and manage data. The system stores multiple database tables that relate to each other. MS SQL Server, MySQL, or MS Access are examples of relational database management systems. The following are the components of such a system. - -### SQL table - -A SQL table is the basic element of a relational database. The SQL database table consists of rows and columns. Database engineers create relationships between multiple database tables to optimize data storage space. - -For example, the database engineer creates a SQL table for products in a store: -![image](https://media.geeksforgeeks.org/wp-content/uploads/20230405171604/Screenshot-from-2023-04-05-17-15-53.png) - -### SQL statements - -SQL statements, or SQL queries, are valid instructions that relational database management systems understand. Software developers build SQL statements by using different SQL language elements. SQL language elements are components such as identifiers, variables, and search conditions that form a correct SQL statement. - -For example, the following SQL statement uses a SQL INSERT command to store Mattress Brand A, priced $499, into a table named Mattress_table, with column names brand_name and cost: - -INSERT INTO Mattress_table (brand_name, cost) - -`VALUES(‘A’,’499’);` - -### Stored procedures - -Stored procedures are a collection of one or more SQL statements stored in the relational database. Software developers use stored procedures to improve efficiency and performance. For example, they can create a stored procedure for updating sales tables instead of writing the same SQL statement in different applications. - -## What are SQL commands? - -Structured query language (SQL) commands are specific keywords or SQL statements that developers use to manipulate the data stored in a relational database. You can categorize SQL commands as follows. - -### Data definition language - -Data definition language (DDL) refers to SQL commands that design the database structure. Database engineers use DDL to create and modify database objects based on the business requirements. For example, the database engineer uses the CREATE command to create database objects such as tables, views, and indexes. - -### Data query language - -Data query language (DQL) consists of instructions for retrieving data stored in relational databases. Software applications use the SELECT command to filter and return specific results from a SQL table. - -### Data manipulation language - -Data manipulation language (DML) statements write new information or modify existing records in a relational database. For example, an application uses the INSERT command to store a new record in the database. - -### Data control language - -Database administrators use data control language (DCL) to manage or authorize database access for other users. For example, they can use the GRANT command to permit certain applications to manipulate one or more tables. - -### Transaction control language - -The relational engine uses transaction control language (TCL) to automatically make database changes. For example, the database uses the ROLLBACK command to undo an erroneous transaction. - -## What is MySQL? - -MySQL is an open-source relational database management system offered by Oracle. Developers can download and use MySQL without paying a licensing fee. They can install MySQL on different operating systems or cloud servers. MySQL is a popular database system for web applications. - -### SQL vs. MySQL - -Structured query language (SQL) is a standard language for database creation and manipulation. MySQL is a relational database program that uses SQL queries. While SQL commands are defined by international standards, the MySQL software undergoes continual upgrades and improvements. - -## What is NoSQL? - -NoSQL refers to non-relational databases that don't use tables to store data. Developers store information in different types of NoSQL databases, including graphs, documents, and key-values. NoSQL databases are popular for modern applications because they are horizontally scalable. Horizontal scaling means increasing the processing power by adding more computers that run NoSQL software. - -### SQL vs. NoSQL - -Structured query language (SQL) provides a uniform data manipulation language, but NoSQL implementation is dependent on different technologies. Developers use SQL for transactional and analytical applications, whereas NoSQL is suitable for responsive, heavy-usage applications. - -## Advantages of SQL - -SQL provides various advantages which make it more popular in the field of data science. It is a perfect query language which allows data professionals and users to communicate with the database. Following are the best advantages or benefits of Structured Query Language: - -1. No programming needed - -SQL does not require a large number of coding lines for managing the database systems. We can easily access and maintain the database by using simple SQL syntactical rules. These simple rules make the SQL user-friendly. - -2. High-Speed Query Processing - -A large amount of data is accessed quickly and efficiently from the database by using SQL queries. Insertion, deletion, and updation operations on data are also performed in less time. - -3. Standardized Language - -SQL follows the long-established standards of ISO and ANSI, which offer a uniform platform across the globe to all its users. - -4. Portability - -The structured query language can be easily used in desktop computers, laptops, tablets, and even smartphones. It can also be used with other applications according to the user's requirements. - -5. Interactive language - -We can easily learn and understand the SQL language. We can also use this language for communicating with the database because it is a simple query language. This language is also used for receiving the answers to complex queries in a few seconds. - -6. More than one Data View - -The SQL language also helps in making the multiple views of the database structure for the different database users. - -## Disadvantages of SQL - -With the advantages of SQL, it also has some disadvantages, which are as follows: - -1. Cost - -The operation cost of some SQL versions is high. That's why some programmers cannot use the Structured Query Language. - -2. Interface is Complex - -Another big disadvantage is that the interface of Structured query language is difficult, which makes it difficult for SQL users to use and manage it. - -3. Partial Database control - -The business rules are hidden. So, the data professionals and users who are using this query language cannot have full database control. diff --git a/blog/tags.yml b/blog/tags.yml deleted file mode 100644 index 836e4c816..000000000 --- a/blog/tags.yml +++ /dev/null @@ -1,244 +0,0 @@ -hola: - label: 'Hola' - permalink: '/hola' - description: 'Articles on the topic hola' - -hello: - label: 'Hello' - permalink: '/hello' - description: 'Articles on the topic hello' - -docusaurus: - label: 'Docusaurus' - permalink: '/docusaurus' - description: 'Articles on the topic docusaurus' - -facebook: - label: 'Facebook' - permalink: '/facebook' - description: 'Articles on the topic facebook' - -react: - label: 'React' - permalink: '/react' - description: 'Articles on the topic react' - -javascript: - label: 'JavaScript' - permalink: '/javascript' - description: 'Articles on the topic javascript' - -typescript: - label: 'TypeScript' - permalink: '/typescript' - description: 'Articles on the topic typescript' - -graphql: - label: 'GraphQL' - permalink: '/graphql' - description: 'Articles on the topic graphql' - -css: - label: 'CSS' - permalink: '/css' - description: 'Articles on the topic css' - -html: - label: 'HTML' - permalink: '/html' - description: 'Articles on the topic html' - -python: - label: 'Python' - permalink: '/python' - description: 'Articles on the topic python' - -java: - label: 'Java' - permalink: '/java' - description: 'Articles on the topic java' - -sql: - label: 'SQL' - permalink: '/sql' - description: 'Articles on the topic sql' - -databases: - label: 'Databases' - permalink: '/databases' - description: 'Articles on the topic databases' - -data: - label: 'Data' - permalink: '/data' - description: 'Articles on the topic data' - -cloud: - label: 'Cloud' - permalink: '/cloud' - description: 'Articles on the topic cloud' - -quantum: - label: 'Quantum' - permalink: '/quantum' - description: 'Articles on the topic quantum computing' - -applications: - label: 'Applications' - permalink: '/applications' - description: 'Articles on the topic applications' - -computing: - label: 'Computing' - permalink: '/computing' - description: 'Articles on the topic computing' - -ai: - label: 'AI' - permalink: '/ai' - description: 'Articles on the topic ai' - -privacy: - label: 'Privacy' - permalink: '/privacy' - description: 'Articles on the topic privacy' - -machine-learning: - label: 'Machine Learning' - permalink: '/machine-learning' - description: 'Articles on the topic Machine Learning' - -cryptography: - label: 'Cryptography' - permalink: '/cryptography' - description: 'Articles on the topic Cryptography' - -cyber-security: - label: 'Cyber Security' - permalink: '/cyber-security' - description: 'Articles on the topic Cyber Security' - -encryption: - label: 'Encryption' - permalink: '/encryption' - description: 'Articles on the topic Encryption' - -technology: - label: 'Technology' - permalink: '/technology' - description: 'Articles on the topic Technology' - -webassembly: - label: 'WebAssembly' - permalink: '/webassembly' - description: 'Articles on the topic WebAssembly' - -wasm: - label: 'WASM' - permalink: '/wasm' - description: 'Articles on the topic WASM' - -web-performance: - label: 'Web Performance' - permalink: '/web-performance' - description: 'Articles on the topic Web Performance' - -iot: - label: 'IoT' - permalink: '/iot' - description: 'Articles on the topic Internet of Things' - -internet-of-things: - label: 'Internet of Things' - permalink: '/internet-of-things' - description: 'Articles on the topic Internet of Things' - -sensors: - label: 'Sensors' - permalink: '/sensors' - description: 'Articles on the topic Sensors' - -actuators: - label: 'Actuators' - permalink: '/actuators' - description: 'Articles on the topic Actuators' - -edge-computing: - label: 'Edge Computing' - permalink: '/edge-computing' - description: 'Articles on the topic Edge Computing' - -microservices: - label: 'Microservices' - permalink: '/microservices' - description: 'Articles on the topic Microservices' - -architecture: - label: 'Architecture' - permalink: '/architecture' - description: 'Articles on the topic Software Architecture' - -spring-boot: - label: 'Spring Boot' - permalink: '/spring-boot' - description: 'Articles on the topic Spring Boot' - -docker: - label: 'Docker' - permalink: '/docker' - description: 'Articles on the topic Docker' - -kubernetes: - label: 'Kubernetes' - permalink: '/kubernetes' - description: 'Articles on the topic Kubernetes' - -monitoring: - label: 'Monitoring' - permalink: '/monitoring' - description: 'Articles on the topic Monitoring' - -linux: - label: 'Linux' - permalink: '/linux' - description: 'Articles on the topic Linux' - -internet: - label: 'Internet' - permalink: '/internet' - description: 'Articles on the topic Internet' - -dev: - label: 'Dev' - permalink: '/dev' - description: 'Articles on the topic Dev' - -tailwind: - label: 'Tailwind' - permalink: '/tailwind' - description: 'Articles on the topic Tailwind' - -shadcn: - label: 'Shadcn' - permalink: '/shadcn' - description: 'Articles on the topic Shadcn' - -mdx: - label: 'MDX' - permalink: '/mdx' - description: 'Articles on the topic MDX' - -js: - label: 'JavaScript' - permalink: '/js' - description: 'Articles on the topic JavaScript' - -node-js: - label: 'Node.js' - permalink: '/node-js' - description: 'Articles on the topic Node.js' - -react-js: - label: 'React JS' - permalink: '/react-js' - description: 'Articles on the topic React JS' \ No newline at end of file diff --git a/docs/Linux/Basic-Command.md b/docs/Linux/Basic-Command.md deleted file mode 100644 index 88557f743..000000000 --- a/docs/Linux/Basic-Command.md +++ /dev/null @@ -1,62 +0,0 @@ -# Basics of Linux - -## Navigating the File System - -- `pwd`: Print the current working directory. -- `ls`: List directory contents. -- `cd `: Change to the specified directory. -- `mkdir `: Create a new directory. -- `rmdir `: Removes an empty directory. - -## File Operations - -- `touch `: Create a new empty file. -- `cp `: Copy files or directories. -- `mv `: Move or rename files or directories. -- `rm `: Remove files. -- `rm -r `: Remove directories and their contents. - -## Viewing and Editing Files - -- `cat `: Display the contents of a file. -- `less `: View file contents page by page. -- `nano `: Edit files using the Nano text editor. -- `vi `: Edit files using the Vi text editor. - -## System Information - -- `uname -a`: Display system information. -- `top`: Display running processes. -- `df -h`: Display disk space usage. -- `free -h`: Display memory usage. - -## File System Structure - -Linux has a hierarchical file system. Key directories include: - -- `/`: Root directory. -- `/home`: User home directories. -- `/bin`: Essential user binaries. -- `/sbin`: System binaries. -- `/etc`: Configuration files. -- `/var`: Variable data files. -- `/tmp`: Temporary files. -- `/usr`: User programs. - -## Permissions - -Linux controls access to files and directories using a permission system. Permissions are divided into read (r), write (w), and execute (x) for the owner, group, and others. - -- `chmod 755 `: Set read, write, and execute permissions for the owner, and read and execute permissions for the group and others. -- `chown user:group `: Change the owner to `user` and the group to `group`. - -## Package Management - -Linux distributions use package managers to install, update, and remove software. - -### Debian-based (e.g., Ubuntu) -- `apt-get update`: Update package index. -- `apt-get install `: Install a package. -- `apt-get remove `: Remove a package. - - diff --git a/docs/Linux/Introduction.md b/docs/Linux/Introduction.md deleted file mode 100644 index dfb2d7d28..000000000 --- a/docs/Linux/Introduction.md +++ /dev/null @@ -1,26 +0,0 @@ ---- -id: linux-intro -title: Introduction to Linux -sidebar_label: Introduction to Linux -sidebar_position: 8 -tags: [Linux, cmd, shell] -description: "Learn Basics of Linux." ---- - -Just like Windows, iOS, and Mac OS, Linux is an operating system. It was initially created by Linus Torvalds in 1991. It’s totally free and you can change it to make it work just how you want. It’s like a giant toolbox that runs on everything, from phones to computers. In fact, one of the most popular platforms on the planet, Android, is powered by the Linux operating system. Learning Linux is important because it’s everywhere even in the cloud where lots of stuff is stored. And even though it might seem scary at first, getting to know Linux can help you do cool stuff and open up new opportunities in the tech world. - -These applications share the same basic components as, - -- Kernel -- User Space -- Resources - -People with many different job roles used Linux. Writers, Video editors, Analysts, and all kinds of professionals use this for many purposes. Software developers use Linux for their coding and development works. Also, many services on the internet are hosted on Linux servers. - -## What are the fundamentals? - -**The Linux Kernel** - -All operating systems have kernels, but mostly when talking about the OS, we don’t talk about kernels as much as Linux kernels. It is the core of Linux distributors and open-source programs. It is originally released by Linux Torvalds (1991). A kernel is a software that gives the ability to communicate with computer software. This can run on its own and it’s required to run software on a computer. The kernel is part of a working operating system. - -![Linux](https://miro.medium.com/v2/resize:fit:1400/format:webp/1*K2WoP-Pdqec5VqnJ2N058g.png) \ No newline at end of file diff --git a/docs/Linux/Linux-Permission.md b/docs/Linux/Linux-Permission.md deleted file mode 100644 index 1d06aa122..000000000 --- a/docs/Linux/Linux-Permission.md +++ /dev/null @@ -1,92 +0,0 @@ - - -## File Permissions - -In Linux, each file and directory has three types of permissions assigned to it: **read**, **write**, and **execute**. These permissions are represented by characters and determine what actions users and groups can perform on the file. - -### Permission Representation - -- **r**: Read permission allows viewing the contents of a file or listing a directory. -- **w**: Write permission allows modifying the contents of a file or creating, renaming, or deleting files within a directory. -- **x**: Execute permission allows running a file as a program or entering (accessing) a directory. - -### Symbolic Representation - -Permissions are represented in a symbolic notation as follows: - -- **`-`**: Indicates a regular file. -- **`d`**: Indicates a directory. -- **`r`**: Read permission. -- **`w`**: Write permission. -- **`x`**: Execute permission. -- **`-`**: Indicates absence of a permission. - -#### Example: -``` --rw-r--r-- -``` -In this example: -- The owner has read and write permissions (`rw-`). -- The group has read permission (`r--`). -- Others have read permission (`r--`). - -## Changing Permissions - -### `chmod` Command - -The `chmod` command is used to change permissions of files and directories. - -#### Syntax: -```bash -chmod options permissions filename -``` - -#### Example: -```bash -chmod u+x file.txt -``` -This command grants the owner (`u`) execute (`x`) permission on `file.txt`. - -## Ownership - -### `chown` Command - -The `chown` command changes file ownership. - -#### Syntax: -```bash -chown owner:group filename -``` - -#### Example: -```bash -chown john:developers file.txt -``` -This command changes the owner of `file.txt` to `john` and assigns the group `developers`. - -## Special Permissions - -### Set User ID (SUID), Set Group ID (SGID), and Sticky Bit - -- **SUID**: Executes a file with the permissions of the file owner. -- **SGID**: Executes a file with the permissions of the group owner. -- **Sticky Bit**: Restricts deletion of files within a directory to only the owner. - -#### Example: -```bash -chmod +s file.txt -``` -This command sets the SUID bit on `file.txt`. - -## Viewing Permissions - -### `ls` Command - -The `ls` command lists files and directories with their permissions. - -#### Example: -```bash -ls -l file.txt -``` -This command displays detailed information about `file.txt`, including permissions. - diff --git a/docs/Linux/Linux-Redirectors.md b/docs/Linux/Linux-Redirectors.md deleted file mode 100644 index 8844fa24c..000000000 --- a/docs/Linux/Linux-Redirectors.md +++ /dev/null @@ -1,85 +0,0 @@ -1. **`>` (Output Redirection):** - - Redirects the standard output (**stdout**) of a command to a file. If the file exists, it is overwritten. - - ```bash - - command > output.txt - ``` - -2. **`>>` (Append Output):** - - Appends the standard output of a command to a file. If the file doesn't exist, it is created. - - ```bash - - command >> output.txt - ``` - -3. **`<` (Input Redirection):** - - Redirects the standard input (**stdin**) of a command from a file. - - ```bash - - command < input.txt - ``` - -4. **`|` (Pipe):** - - Redirects the output of one command as the input to another command. - - ```bash - - command1 | command2 - - ls | sort | tee sorted_file_list.tx - ``` - -5. **`2>` (Standard Error Redirection):** - - Redirects the standard error (**stderr**) of a command to a file. - - ```bash - - command 2> error.txt - ``` - -6. **`2>>` (Append Standard Error):** - - Appends the standard error of a command to a file. - - ```bash - - command 2>> error.txt - ``` - -7. **`&>` (Redirect Standard Output and Error):** - - Redirects both standard output and standard error to a file. - - ```bash - - command &> output_and_error.txt - ``` - -8. **`2>&1` (Merge Standard Error with Standard Output):** - - Redirects standard error to the same location as standard output. - - ```bash - - command 2>&1 - ``` - -9. **`/dev/null` (Null Device):** - - Discards data. Useful for suppressing output. - - ```bash - - command > /dev/null - - ls /fake/directory 2> /dev/null - ``` - -10. **`tee` (Split Output):** - - Reads from standard input and writes to standard output and files simultaneously. - - ```bash - - command | tee output.txt - - ls | tee peanuts.txt banan.txt - ``` \ No newline at end of file diff --git a/docs/Linux/String-Manipulation.md b/docs/Linux/String-Manipulation.md deleted file mode 100644 index 3d2b21648..000000000 --- a/docs/Linux/String-Manipulation.md +++ /dev/null @@ -1,184 +0,0 @@ -- **STRING MANIPULATION :** Play with strings - 1. **`strings`** : used to extract readable text strings from binary files. When you run **`strings`** on a file, it scans through the binary data looking for sequences of printable characters and displays them. This is often useful for extracting human-readable information from compiled executables or other binary files. - - ```bash - strings data.txt - ``` - - 2. **`env`** : Environment variables in Linux are dynamic values that can affect the behavior of processes and programs running in the operating system. - - ```bash - # display env variables - - $ env - - $ echo $PATH - - /usr/local/sbin:/usr/local/bin:/usr/sbin:/bin - - # This returns a list of paths separated by a colon that your system searches when it runs a command. - - # Modify the path variable - - export PATH=$PATH:/path/to/new/directory - - ``` - - 3. **`cut`** : It is used for cutting out sections from each line of a file or from piped data. - - - - **`c, --characters=LIST`**: Select only these characters. - - **`f, --fields=LIST`**: Select only these fields. - - **`d, --delimiter=DELIM`**: Use DELIM instead of TAB for field delimiter. - - ```bash - # Extract 5th character from each line - cut -c 5 sample.txt - - # Extract characters 3-7 and 12-16 from each line of a file: - cut -c 3-7,12-16 filename.txt - - # Extract the first and third fields (using a comma as the delimiter) from a file - # By default it 'd' is TAB - cut -f 1,3 -d , filename.csv - - # Extract the second field (using a comma as the delimiter) from - # the output of another command: - echo "John,Doe,25" | cut -f 2 -d , - ``` - - 4. **`head`** : By default the head command will show you the first 10 lines in a file. - - The -n flag stands for number of lines. - - ```bash - head -n 15 /var/log/syslog # diaplay first 15 lines - head -c 15 /var/log/syslog # display first 15 characters - - ``` - - 5. **`tail`** : It is similar to head command as it prints the last 10 lines of a file - - ```bash - tail -3 filename # display last 3 lines - tail +3 filename # skips first 2 lines - ``` - - 6. **`paste`** : The paste command is similar to the cat command, it merges lines together in a file. - - **EXAMPLES** - - ```bash - # Display the first 5 lines (head) and the last 5 lines (tail) of a file - paste <(head -n 5 filename.txt) <(tail -n 5 filename.txt) - - # Display the first 3 lines (head) and the last 3 lines (tail) of the ls command - paste <(ls | head -n 3) <(ls | tail -n 3) - ``` - - 7. **`expand`** : To converts your TABs to spaces, use the expand command.(it doesn’t remove space). - 8. **`unexpand`** : Opposite of expand - - ```bash - expand sample.txt > result.txt - unexpand -a result.txt - - tr -s '\t' ' ' < input.txt > output.txt #It will reove tabs & make a single space - tr -s '\n' ' ' < sample.txt # This change the newline into a space - tr -s ';' ' ' < sample.txt # This will change semicolon to space - - **NOTE- This will not change them temporarily, you need to save the output** - ``` - - 9. **`sort`** : sort a file - - **`-r, --reverse`**: Reverse the result of comparisons. - - **`-n, --numeric-sort`**: Sort numerically. - - **`-u, --unique`**: Output only unique lines. - - ```bash - sort filename.txt - - # sort the file and '-m' merge the file - sort -m file1.txt file2.txt file3.txt > sorted_output.txt - - ``` - - 10. **`tr`** : The tr (translate) command allows you to translate a set of characters into another set of characters. - - ```bash - tr a-z A-Z # coverts the lowecase to uppercase - - hello - - HELLO - - echo "123abc456" | tr -d '0-9' # Delete digits from string - ``` - - 11. **`split`** : This will split it into different files, by default it will split them once they reach a 1000 line limit. - - ```bash - # his splits input.txt into files each containing 100 lines. - split -l 100 input.txt - - -l NUMBER: Split the file into chunks of NUMBER lines. - -b SIZE[K|M|G]: Split the file into chunks of specified size. - ``` - - 12. **`join`** : The join command allows you to join multiple files together by a common field: - - ```bash - $ join -1 2 -2 1 file1.txt file2.txt - - 1 John Doe - - 2 Jane Doe - - 3 Mary Sue - ``` - - 13. **`uniq`** : The **`uniq`** (unique) command is another useful tool for parsing text. - - ```bash - uniq reading.txt # remove duplicates - - uniq -c reading.txt # get the count of how many occurrences of a line - - uniq -u reading.txt # get unique values (occur only one time) - - uniq -d reading.txt # get duplicate values - - **Note** : uniq does not detect duplicate lines unless they are adjacent. - - # To overcome this limitation of uniq we can use sort in combination with uniq: - sort reading.txt | uniq - ``` - - 14. **`wc`** : The **`wc`** command stands for "word count" and is used to count the number of lines, words, and characters in a file. - - ```bash - wc myfile.txt - - -l: Count lines. - -w: Count words. - -c: Count characters. - ``` - - 15. **`nl`** : used to number lines in a file - - ```bash - $ nl file1.txt - - 1. i - 2. like - 3. turtles - ``` - - - -## Additional resource - -You can read the blog to get a complete guide to master Linux. - -[Read Blog](https://medium.com/@rajveer_0101/the-ultimate-guide-to-linux-mastery-c691c09b437c) - -[![blog](https://miro.medium.com/v2/resize:fit:1100/format:webp/1*gmCUTP8AXcgZm4-08wUH8g.jpeg)](https://medium.com/@rajveer_0101/the-ultimate-guide-to-linux-mastery-c691c09b437c) - diff --git a/docs/Linux/_category_.json b/docs/Linux/_category_.json deleted file mode 100644 index 88c92033b..000000000 --- a/docs/Linux/_category_.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "label": "Linux", - "position": 13, - "link": { - "type": "generated-index", - "description": "Linux is an open-source operating system that is widely used in various computing environments." - } -} \ No newline at end of file diff --git a/docs/MongoDB/Advanced MongoDB/_category.json b/docs/MongoDB/Advanced MongoDB/_category.json deleted file mode 100644 index 7235a04b4..000000000 --- a/docs/MongoDB/Advanced MongoDB/_category.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "label": "Advanced MongoDB", - "position": 25, - "link": { - "type": "generated-index", - "description": "Dive deeper into advanced MongoDB concepts and techniques." - } -} \ No newline at end of file diff --git a/docs/MongoDB/Advanced MongoDB/mongodb-ObjectId.md b/docs/MongoDB/Advanced MongoDB/mongodb-ObjectId.md deleted file mode 100644 index 4957ddf28..000000000 --- a/docs/MongoDB/Advanced MongoDB/mongodb-ObjectId.md +++ /dev/null @@ -1,69 +0,0 @@ ---- -id: mongodb-ObjectId -title: MongoDB - ObjectId -sidebar_label: ObjectId -sidebar_position: 8 -tags: [mongodb, ObjectId, document identifier] -description: Understand the structure and usage of ObjectId in MongoDB, including creation, timestamp extraction, and conversion to string format. ---- - -We have been using MongoDB ObjectId in all the previous chapters. In this chapter, let's delve into the structure and usage of ObjectId. - -## ObjectId Structure - -An ObjectId is a 12-byte BSON type structured as follows: - -- The first 4 bytes represent the seconds since the Unix epoch. -- The next 3 bytes are the machine identifier. -- The following 2 bytes consist of the process id. -- The last 3 bytes are a random counter value. - -MongoDB utilizes ObjectIds as the default value of the `_id` field of each document, generated during document creation. This intricate combination ensures that all `_id` fields are unique. - -## Creating New ObjectId - -To generate a new ObjectId, use the following code snippet: - -```javascript -newObjectId = ObjectId() -``` - -The above statement will return a uniquely generated id like: - -``` -ObjectId("5349b4ddd2781d08c09890f3") -``` - -Alternatively, you can provide a 12-byte id explicitly: - -```javascript -myObjectId = ObjectId("5349b4ddd2781d08c09890f4") -``` - -## Creating Timestamp of a Document - -As the `_id` ObjectId inherently stores the 4-byte timestamp, you typically don't need to store the creation time of any document separately. You can retrieve the creation time of a document using the `getTimestamp` method: - -```javascript -ObjectId("5349b4ddd2781d08c09890f4").getTimestamp() -``` - -This will return the creation time of the document in ISO date format: - -``` -ISODate("2014-04-12T21:49:17Z") -``` - -## Converting ObjectId to String - -In certain scenarios, you may require the ObjectId value in a string format. To convert the ObjectId to a string, use the following code: - -```javascript -newObjectId.str -``` - -The above code will provide the string format of the ObjectId, such as: - -``` -5349b4ddd2781d08c09890f3 -``` diff --git a/docs/MongoDB/Advanced MongoDB/mongodb-advanced-indexing.md b/docs/MongoDB/Advanced MongoDB/mongodb-advanced-indexing.md deleted file mode 100644 index 17d1afc4f..000000000 --- a/docs/MongoDB/Advanced MongoDB/mongodb-advanced-indexing.md +++ /dev/null @@ -1,233 +0,0 @@ ---- -id: mongodb-advanced-indexing -title: MongoDB - Advanced Indexing -sidebar_label: Advanced Indexing -sidebar_position: 6 -tags: [mongodb, indexing, array indexing, sub-document indexing] -description: Learn how to create advanced indexes in MongoDB, including indexing array fields and sub-document fields for optimized query performance. ---- - -## Indexing Array Fields - -We have inserted the following document in the collection named `users`: - -```javascript -db.users.insert( - { - "address": { - "city": "Los Angeles", - "state": "California", - "pincode": "123" - }, - "tags": [ - "music", - "cricket", - "blogs" - ], - "name": "Tom Benzamin" - } -) -``` - -The above document contains an `address` sub-document and a `tags` array. - -### Creating an Index on Array Fields - -Suppose we want to search user documents based on the user’s tags. For this, we will create an index on the `tags` array in the collection. - -Creating an index on an array in turn creates separate index entries for each of its fields. So in our case, when we create an index on the `tags` array, separate indexes will be created for its values `music`, `cricket`, and `blogs`. - -To create an index on the `tags` array, use the following code: - -```javascript -db.users.createIndex({"tags":1}) -``` - -```json -{ - "createdCollectionAutomatically" : false, - "numIndexesBefore" : 2, - "numIndexesAfter" : 3, - "ok" : 1 -} -``` - -After creating the index, we can search on the `tags` field of the collection like this: - -```javascript -db.users.find({tags:"cricket"}).pretty() -``` - -```json -{ - "_id" : ObjectId("5dd7c927f1dd4583e7103fdf"), - "address" : { - "city" : "Los Angeles", - "state" : "California", - "pincode" : "123" - }, - "tags" : [ - "music", - "cricket", - "blogs" - ], - "name" : "Tom Benzamin" -} -``` - -To verify that proper indexing is used, use the following `explain` command: - -```javascript -db.users.find({tags:"cricket"}).explain() -``` - -This gives you the following result: - -```json -{ - "queryPlanner" : { - "plannerVersion" : 1, - "namespace" : "mydb.users", - "indexFilterSet" : false, - "parsedQuery" : { - "tags" : { - "$eq" : "cricket" - } - }, - "queryHash" : "9D3B61A7", - "planCacheKey" : "04C9997B", - "winningPlan" : { - "stage" : "FETCH", - "inputStage" : { - "stage" : "IXSCAN", - "keyPattern" : { - "tags" : 1 - }, - "indexName" : "tags_1", - "isMultiKey" : false, - "multiKeyPaths" : { - "tags" : [ ] - }, - "isUnique" : false, - "isSparse" : false, - "isPartial" : false, - "indexVersion" : 2, - "direction" : "forward", - "indexBounds" : { - "tags" : [ - "[\"cricket\", \"cricket\"]" - ] - } - } - }, - "rejectedPlans" : [ ] - }, - "serverInfo" : { - "host" : "Krishna", - "port" : 27017, - "version" : "4.2.1", - "gitVersion" : "edf6d45851c0b9ee15548f0f847df141764a317e" - }, - "ok" : 1 -} -``` - -The above command resulted in `"stage" : "IXSCAN", "indexName" : "tags_1"` which confirms that proper indexing is used. - -## Indexing Sub-Document Fields - -Suppose that we want to search documents based on `city`, `state`, and `pincode` fields. Since all these fields are part of the `address` sub-document field, we will create an index on all the fields of the sub-document. - -For creating an index on all the three fields of the sub-document, use the following code: - -```javascript -db.users.createIndex({"address.city":1,"address.state":1,"address.pincode":1}) -``` - -```json -{ - "numIndexesBefore" : 4, - "numIndexesAfter" : 4, - "note" : "all indexes already exist", - "ok" : 1 -} -``` - -Once the index is created, we can search for any of the sub-document fields utilizing this index as follows: - -```javascript -db.users.find({"address.city":"Los Angeles"}).pretty() -``` - -```json -{ - "_id" : ObjectId("5dd7c927f1dd4583e7103fdf"), - "address" : { - "city" : "Los Angeles", - "state" : "California", - "pincode" : "123" - }, - "tags" : [ - "music", - "cricket", - "blogs" - ], - "name" : "Tom Benzamin" -} -``` - -Remember that the query expression has to follow the order of the index specified. So the index created above would support the following queries: - -```javascript -db.users.find({"address.city":"Los Angeles","address.state":"California"}).pretty() -``` - -```json -{ - "_id" : ObjectId("5dd7c927f1dd4583e7103fdf"), - "address" : { - "city" : "Los Angeles", - "state" : "California", - "pincode" : "123" - }, - "tags" : [ - "music", - "cricket", - "blogs" - ], - "name" : "Tom Benzamin" -} -``` - -### Diagram (Mermaid) - -Here is a visual representation of the document structure and indexing process: - -```mermaid -graph TD; - A[Document: users] - A --> B[Sub-document: address] - A --> C[Array: tags] - B --> D[city] - B --> E[state] - B --> F[pincode] - C --> G[music] - C --> H[cricket] - C --> I[blogs] -``` - -### Notes - -- Indexing array fields in MongoDB creates separate index entries for each value in the array. -- Indexing sub-document fields allows efficient queries on nested fields. -- Ensure the query order matches the index order to fully utilize the indexes. - -### Table - -| Field | Type | Indexed | Description | -|-----------------|------------------|---------|------------------------------------------| -| `address` | Sub-document | Yes | Contains nested fields for address info. | -| `address.city` | String | Yes | City name in the address. | -| `address.state` | String | Yes | State name in the address. | -| `address.pincode`| String | Yes | Pincode in the address. | -| `tags` | Array of Strings | Yes | User's tags for indexing. | diff --git a/docs/MongoDB/Advanced MongoDB/mongodb-analyzing-queries.md b/docs/MongoDB/Advanced MongoDB/mongodb-analyzing-queries.md deleted file mode 100644 index d5d87733e..000000000 --- a/docs/MongoDB/Advanced MongoDB/mongodb-analyzing-queries.md +++ /dev/null @@ -1,196 +0,0 @@ ---- -id: mongodb-analyzing-queries -title: MongoDB - Analyzing Queries -sidebar_label: Analyzing Queries -sidebar_position: 4 -tags: [mongodb, analyzing queries, $explain, $hint] -description: Learn how to analyze MongoDB queries using $explain and $hint operators to optimize database performance. ---- - -# MongoDB - Analyzing Queries - -Analyzing queries is a very important aspect of measuring how effective the database and indexing design is. We will learn about the frequently used `$explain` and `$hint` queries. - -## Using $explain - -The `$explain` operator provides information on the query, indexes used in a query, and other statistics. It is very useful when analyzing how well your indexes are optimized. - -In the last chapter, we had already created an index for the `users` collection on fields `gender` and `user_name` using the following query: - -```mongodb -db.users.createIndex({gender:1,user_name:1}) -{ - "numIndexesBefore" : 2, - "numIndexesAfter" : 2, - "note" : "all indexes already exist", - "ok" : 1 -} -``` - -We will now use `$explain` on the following query: - -```mongodb -db.users.find({gender:"M"},{user_name:1,_id:0}).explain() -``` - -The above `explain()` query returns the following analyzed result: - -```json -{ - "queryPlanner" : { - "plannerVersion" : 1, - "namespace" : "mydb.users", - "indexFilterSet" : false, - "parsedQuery" : { - "gender" : { - "$eq" : "M" - } - }, - "queryHash" : "B4037D3C", - "planCacheKey" : "DEAAE17C", - "winningPlan" : { - "stage" : "PROJECTION_COVERED", - "transformBy" : { - "user_name" : 1, - "_id" : 0 - }, - "inputStage" : { - "stage" : "IXSCAN", - "keyPattern" : { - "gender" : 1, - "user_name" : 1 - }, - "indexName" : "gender_1_user_name_1", - "isMultiKey" : false, - "multiKeyPaths" : { - "gender" : [ ], - "user_name" : [ ] - }, - "isUnique" : false, - "isSparse" : false, - "isPartial" : false, - "indexVersion" : 2, - "direction" : "forward", - "indexBounds" : { - "gender" : [ - "[\"M\", \"M\"]" - ], - "user_name" : [ - "[MinKey, MaxKey]" - ] - } - } - }, - "rejectedPlans" : [ ] - }, - "serverInfo" : { - "host" : "Krishna", - "port" : 27017, - "version" : "4.2.1", - "gitVersion" : "edf6d45851c0b9ee15548f0f847df141764a317e" - }, - "ok" : 1 -} -``` - -We will now look at the fields in this result set: - -- **queryPlanner:** Contains details about the query plan, indexes used, and stages involved in executing the query. -- **indexOnly:** Indicates whether the query was covered by an index. -- **cursor:** Specifies the type of cursor used (e.g., `BTreeCursor` for indexed queries). -- **n:** Indicates the number of documents matching the query. -- **nscannedObjects:** Indicates the total number of documents scanned. -- **nscanned:** Indicates the total number of documents or index entries scanned. - -## Using $hint - -The `$hint` operator forces the query optimizer to use the specified index to run a query. This is particularly useful when you want to test the performance of a query with different indexes. For example, the following query specifies the index on fields `gender` and `user_name` to be used for this query: - -```mongodb -db.users.find({gender:"M"},{user_name:1,_id:0}).hint({gender:1,user_name:1}) -{ "user_name" : "tombenzamin" } -``` - -To analyze the above query using `$explain`: - -```mongodb -db.users.find({gender:"M"},{user_name:1,_id:0}).hint({gender:1,user_name:1}).explain() -``` - -Which gives you the following result: - -```json -{ - "queryPlanner" : { - "plannerVersion" : 1, - "namespace" : "mydb.users", - "indexFilterSet" : false, - "parsedQuery" : { - "gender" : { - "$eq" : "M" - } - }, - "queryHash" : "B4037D3C", - "planCacheKey" : "DEAAE17C", - "winningPlan" : { - "stage" : "PROJECTION_COVERED", - "transformBy" : { - "user_name" : 1, - "_id" : 0 - }, - "inputStage" : { - "stage" : "IXSCAN", - "keyPattern" : { - "gender" : 1, - "user_name" : 1 - }, - "indexName" : "gender_1_user_name_1", - "isMultiKey" : false, - "multiKeyPaths" : { - "gender" : [ ], - "user_name" : [ ] - }, - "isUnique" : false, - "isSparse" : false, - "isPartial" : false, - "indexVersion" : 2, - "direction" : "forward", - "indexBounds" : { - "gender" : [ - "[\"M\", \"M\"]" - ], - "user_name" : [ - "[MinKey, MaxKey]" - ] - } - } - }, - "rejectedPlans" : [ ] - }, - "serverInfo" : { - "host" : "Krishna", - "port" : 27017, - "version" : "4.2.1", - "gitVersion" : "edf6d45851c0b9ee15548f0f847df141764a317e" - }, - "ok" : 1 -} -``` - -## Diagram - -```mermaid -graph TD - A[Query] --> B[$explain] - A --> C[$hint] - B --> D[Query Plan] - C --> D - D --> E[Optimization] -``` - -## Summary Table - -| Operator | Description | Usage Example | -|-----------|-----------------------------------------------------------------|---------------------------------------------------------------------------------------------------------| -| $explain | Provides information on query execution, indexes used, and stats| `db.users.find({gender:"M"},{user_name:1,_id:0}).explain()` | -| $hint | Forces the query to use a specified index | `db.users.find({gender:"M"},{user_name:1,_id:0}).hint({gender:1,user_name:1})` | diff --git a/docs/MongoDB/Advanced MongoDB/mongodb-atomic-operations.md b/docs/MongoDB/Advanced MongoDB/mongodb-atomic-operations.md deleted file mode 100644 index 10310acc2..000000000 --- a/docs/MongoDB/Advanced MongoDB/mongodb-atomic-operations.md +++ /dev/null @@ -1,92 +0,0 @@ ---- -id: mongodb-atomic-operations -title: MongoDB - Atomic Operations -sidebar_label: Atomic Operations -sidebar_position: 5 -tags: [mongodb, atomic operations, findAndModify, embedded documents] -description: Learn how to maintain atomicity in MongoDB by using embedded documents and the findAndModify command for atomic operations. ---- - -# MongoDB - Atomic Operations - -## Model Data for Atomic Operations - -The recommended approach to maintain atomicity is to keep all related information, which is frequently updated together, in a single document using embedded documents. This ensures that all updates for a single document are atomic. - -### Example Scenario - -Assume we have created a collection named `products` and inserted a document in it as shown below: - -```javascript -> db.createCollection("products") -{ "ok" : 1 } - -> db.productDetails.insert({ - "_id": 1, - "product_name": "Samsung S3", - "category": "mobiles", - "product_total": 5, - "product_available": 3, - "product_bought_by": [ - { - "customer": "john", - "date": "7-Jan-2014" - }, - { - "customer": "mark", - "date": "8-Jan-2014" - } - ] -}) -WriteResult({ "nInserted" : 1 }) -``` - -In this document, we have embedded the information of the customer who buys the product in the `product_bought_by` field. Whenever a new customer buys the product, we will first check if the product is still available using the `product_available` field. If available, we will reduce the value of the `product_available` field and insert the new customer's embedded document in the `product_bought_by` field. We will use the `findAndModify` command for this functionality because it searches and updates the document in one go. - -### Atomic Update Example - -```javascript -> db.products.findAndModify({ - query: { _id: 2, product_available: { $gt: 0 } }, - update: { - $inc: { product_available: -1 }, - $push: { product_bought_by: { customer: "rob", date: "9-Jan-2014" } } - } -}) -``` - -Our approach of using embedded documents and the `findAndModify` query ensures that the product purchase information is updated only if the product is available. The whole transaction, being in a single query, is atomic. - -### Non-Atomic Update Example - -In contrast, consider a scenario where we keep the product availability and the purchase information separately. In this case, we first check if the product is available using the first query. Then, in the second query, we update the purchase information. However, it is possible that between the executions of these two queries, another user has purchased the product and it is no longer available. Without knowing this, our second query will update the purchase information based on the result of our first query. This will make the database inconsistent because we have sold a product that is not available. - -### Atomic Operations Diagram - -```mermaid -graph TD; - A[Start] --> B{Check product availability} - B -->|Available| C[Decrease product_available] - C --> D[Add customer to product_bought_by] - D --> E[Operation Successful] - B -->|Not Available| F[Operation Failed] -``` - -### Key Points - -- **Atomicity:** Ensuring all related updates are performed together. -- **Embedded Documents:** Keeping frequently updated related information in a single document. -- **findAndModify:** A MongoDB command to search and update a document in one atomic operation. - -### Table: findAndModify Command - -| Field | Description | -|-------------------|--------------------------------------------------| -| `query` | The selection criteria for the document to update| -| `update` | The modifications to apply | -| `$inc` | Increment a field value | -| `$push` | Append a value to an array | -| `product_available` | Number of products available | -| `product_bought_by` | Array of customers who bought the product | - -By embedding related data and using atomic operations like `findAndModify`, MongoDB ensures data consistency and integrity, even in complex transactions. diff --git a/docs/MongoDB/Advanced MongoDB/mongodb-covered-queries.md b/docs/MongoDB/Advanced MongoDB/mongodb-covered-queries.md deleted file mode 100644 index 5ae2157a4..000000000 --- a/docs/MongoDB/Advanced MongoDB/mongodb-covered-queries.md +++ /dev/null @@ -1,86 +0,0 @@ ---- -id: mongodb-covered-queries -title: MongoDB - Covered Queries -sidebar_label: Covered Queries -sidebar_position: 3 -tags: [mongodb, covered queries, indexes] -description: Learn about covered queries in MongoDB and how to use them for optimized performance. ---- - -# MongoDB - Covered Queries - -In this chapter, we will learn about covered queries. - -## What is a Covered Query? - -As per the official MongoDB documentation, a covered query is a query in which − - -- All the fields in the query are part of an index. -- All the fields returned in the query are in the same index. - -Since all the fields present in the query are part of an index, MongoDB matches the query conditions and returns the result using the same index without actually looking inside the documents. Since indexes are present in RAM, fetching data from indexes is much faster as compared to fetching data by scanning documents. - -## Using Covered Queries - -To test covered queries, consider the following document in the `users` collection − - -```json -{ - "_id": ObjectId("53402597d852426020000003"), - "contact": "987654321", - "dob": "01-01-1991", - "gender": "M", - "name": "Tom Benzamin", - "user_name": "tombenzamin" -} -``` - -We will first create a compound index for the `users` collection on the fields `gender` and `user_name` using the following query − - -```mongodb -db.users.createIndex({gender:1,user_name:1}) -{ - "createdCollectionAutomatically" : false, - "numIndexesBefore" : 1, - "numIndexesAfter" : 2, - "ok" : 1 -} -``` - -Now, this index will cover the following query − - -```mongodb -db.users.find({gender:"M"},{user_name:1,_id:0}) -{ "user_name" : "tombenzamin" } -``` - -That is to say that for the above query, MongoDB would not go looking into database documents. Instead, it would fetch the required data from indexed data which is very fast. - -Since our index does not include `_id` field, we have explicitly excluded it from the result set of our query, as MongoDB by default returns `_id` field in every query. So the following query would not have been covered inside the index created above − - -```mongodb -db.users.find({gender:"M"},{user_name:1}) -{ "_id" : ObjectId("53402597d852426020000003"), "user_name" : "tombenzamin" } -``` - -Lastly, remember that an index cannot cover a query if − - -- Any of the indexed fields is an array. -- Any of the indexed fields is a subdocument. - -## Diagram - -```mermaid -graph TD - A[Query] --> B[Indexes] - B --> C[Results] - A -->|Direct| C - C -->|Faster| D[Performance] -``` - -## Summary Table - -| Query Type | Description | Performance Impact | -|------------------|-----------------------------------------------------------------------------------------|-----------------------------------------| -| Covered Query | All fields in query and result are part of an index | High - Utilizes indexes only, faster | -| Non-Covered Query| Fields in query or result are not entirely part of an index, may require document scan | Lower - May need to scan documents | diff --git a/docs/MongoDB/Advanced MongoDB/mongodb-database-references.md b/docs/MongoDB/Advanced MongoDB/mongodb-database-references.md deleted file mode 100644 index c7e5f8075..000000000 --- a/docs/MongoDB/Advanced MongoDB/mongodb-database-references.md +++ /dev/null @@ -1,79 +0,0 @@ ---- -id: mongodb-database-references -title: MongoDB - Database References -sidebar_label: Database References -sidebar_position: 2 -tags: [mongodb, dbref, references, manual references] -description: Learn how to use database references (DBRefs) in MongoDB. ---- - -# MongoDB - Database References - -As seen in the last chapter of MongoDB relationships, to implement a normalized database structure in MongoDB, we use the concept of Referenced Relationships, also referred to as Manual References, in which we manually store the referenced document's id inside another document. However, in cases where a document contains references from different collections, we can use MongoDB DBRefs. - -## DBRefs vs Manual References - -As an example scenario, where we would use DBRefs instead of manual references, consider a database where we are storing different types of addresses (home, office, mailing, etc.) in different collections (address_home, address_office, address_mailing, etc). Now, when a user collection's document references an address, it also needs to specify which collection to look into based on the address type. In such scenarios where a document references documents from many collections, we should use DBRefs. - -## Using DBRefs - -There are three fields in DBRefs − - -- **$ref** − This field specifies the collection of the referenced document. -- **$id** − This field specifies the `_id` field of the referenced document. -- **$db** − This is an optional field and contains the name of the database in which the referenced document lies. - -Consider a sample user document having DBRef field `address` as shown in the code snippet − - -```json -{ - "_id":ObjectId("53402597d852426020000002"), - "address": { - "$ref": "address_home", - "$id": ObjectId("534009e4d852427820000002"), - "$db": "tutorialspoint" - }, - "contact": "987654321", - "dob": "01-01-1991", - "name": "Tom Benzamin" -} -``` - -The `address` DBRef field here specifies that the referenced address document lies in `address_home` collection under `tutorialspoint` database and has an id of `534009e4d852427820000002`. - -The following code dynamically looks in the collection specified by `$ref` parameter (address_home in our case) for a document with id as specified by `$id` parameter in DBRef. - -```mongodb -var user = db.users.findOne({"name":"Tom Benzamin"}) -var dbRef = user.address -db[dbRef.$ref].findOne({"_id":(dbRef.$id)}) -``` - -The above code returns the following address document present in `address_home` collection − - -```json -{ - "_id" : ObjectId("534009e4d852427820000002"), - "building" : "22 A, Indiana Apt", - "pincode" : 123456, - "city" : "Los Angeles", - "state" : "California" -} -``` - -## Diagram - -```mermaid -graph TD - A[User Document] -->|Manual Reference| B[Address Document] - A -->|DBRef| C[Address Home Collection] - A -->|DBRef| D[Address Office Collection] - A -->|DBRef| E[Address Mailing Collection] -``` - -## Summary Table - -| Approach | Description | Pros | Cons | -|--------------------|---------------------------------------------------------------------------------|---------------------------------------------|----------------------------------------------------| -| Manual References | Store the referenced document's id inside another document | Simple to implement, straightforward | Requires multiple queries, no collection context | -| DBRefs | Store references with `$ref`, `$id`, and `$db` fields specifying collection and id | Includes collection context, more dynamic | Slightly more complex, still requires multiple queries | diff --git a/docs/MongoDB/Advanced MongoDB/mongodb-indexing-limitations.md b/docs/MongoDB/Advanced MongoDB/mongodb-indexing-limitations.md deleted file mode 100644 index 232eef715..000000000 --- a/docs/MongoDB/Advanced MongoDB/mongodb-indexing-limitations.md +++ /dev/null @@ -1,109 +0,0 @@ ---- -id: mongodb-indexing-limitations -title: MongoDB - Indexing Limitations -sidebar_label: Indexing Limitations -sidebar_position: 7 -tags: [mongodb, indexing, limitations, performance] -description: Understand the limitations of indexing in MongoDB, including overhead, RAM usage, query constraints, and key limits. ---- - -# MongoDB - Indexing Limitations - -In this chapter, we will learn about Indexing Limitations and its other components. - -## Extra Overhead - -Every index occupies some space as well as causes an overhead on each insert, update and delete. So if you rarely use your collection for read operations, it makes sense not to use indexes. - -:::note -- Indexes require additional space. -- Each insert, update, and delete operation requires additional processing due to index maintenance. -::: - -```mermaid -graph TD; - A[Insert Operation] --> B[Index Overhead]; - C[Update Operation] --> B; - D[Delete Operation] --> B; -``` - -## RAM Usage - -Since indexes are stored in RAM, you should make sure that the total size of the index does not exceed the RAM limit. If the total size increases the RAM size, it will start deleting some indexes, causing performance loss. - -:::note - Ensure that the total size of all indexes does not exceed the available RAM to avoid performance issues. -::: - -```mermaid -graph TD; - A[Indexes] -->|Stored in| B[RAM]; - B -->|Exceeds| C[Performance Loss]; - C --> D[Deletes Some Indexes]; -``` - -## Query Limitations - -Indexing can't be used in queries which use: -- Regular expressions or negation operators like `$nin`, `$not`, etc. -- Arithmetic operators like `$mod`, etc. -- `$where` clause - -:::note -- Regular expressions and negation operators cannot use indexes. -- Arithmetic operators and `$where` clause cannot use indexes. -::: - -| Query Type | Index Usage | -|-----------------|--------------| -| Regular Expressions | Not Supported | -| Negation Operators | Not Supported | -| Arithmetic Operators | Not Supported | -| `$where` Clause | Not Supported | - -## Index Key Limits - -Starting from version 2.6, MongoDB will not create an index if the value of existing index field exceeds the index key limit. - -> **Note:** Index creation is restricted if any field value exceeds the index key limit. - -```mermaid -graph TD; - A[Index Creation] -->|Value exceeds limit| B[Not Created]; -``` - -## Inserting Documents Exceeding Index Key Limit - -MongoDB will not insert any document into an indexed collection if the indexed field value of this document exceeds the index key limit. The same is the case with `mongorestore` and `mongoimport` utilities. - -:::note - Documents with indexed field values exceeding the key limit will not be inserted into an indexed collection. -::: - -```mermaid -graph TD; - A[Document Insertion] -->|Exceeds Key Limit| B[Insertion Failed]; - C[mongorestore] -->|Exceeds Key Limit| B; - D[mongoimport] -->|Exceeds Key Limit| B; -``` - -## Maximum Ranges - -- A collection cannot have more than 64 indexes. -- The length of the index name cannot be longer than 125 characters. -- A compound index can have a maximum of 31 fields indexed. - -> **Table: Maximum Ranges** - -| Limit Type | Maximum Value | -|--------------------------|---------------------| -| Number of Indexes | 64 | -| Length of Index Name | 125 Characters | -| Fields in Compound Index | 31 Fields | - -```mermaid -graph TD; - A[Maximum Ranges] --> B[64 Indexes per Collection]; - A --> C[125 Characters Index Name]; - A --> D[31 Fields in Compound Index]; -``` diff --git a/docs/MongoDB/Advanced MongoDB/mongodb-map-reduce.md b/docs/MongoDB/Advanced MongoDB/mongodb-map-reduce.md deleted file mode 100644 index b026fdd61..000000000 --- a/docs/MongoDB/Advanced MongoDB/mongodb-map-reduce.md +++ /dev/null @@ -1,109 +0,0 @@ ---- -id: mongodb-map-reduce -title: MongoDB - Map Reduce -sidebar_label: Map Reduce -sidebar_position: 9 -tags: [mongodb, map reduce, data processing] -description: Understand the MapReduce paradigm in MongoDB for condensing large volumes of data into useful aggregated results. ---- - -According to MongoDB documentation, MapReduce is a data processing paradigm used to condense large data sets into useful aggregated results. MongoDB employs the `mapReduce` command for map-reduce operations, primarily for processing substantial data sets. - -## MapReduce Command Syntax - -The basic syntax of the `mapReduce` command in MongoDB is as follows: - -```javascript -db.collection.mapReduce( - function() {emit(key,value);}, // map function - function(key,values) {return reduceFunction;}, // reduce function - { // options - out: collection, // specifies the location of the query result - query: document, // optional selection criteria for documents - sort: document, // optional sort criteria - limit: number // optional maximum number of documents to return - } -) -``` - -In the above syntax: - -- `map` is a JavaScript function that maps a value with a key and emits a key-value pair. -- `reduce` is a JavaScript function that reduces or groups documents with the same key. -- `out` specifies the location of the map-reduce query result. -- `query` specifies optional selection criteria for selecting documents. -- `sort` specifies optional sort criteria. -- `limit` specifies the optional maximum number of documents to return. - -### Using MapReduce - -Consider a document structure storing user posts with fields like `post_text`, `user_name`, and `status`. We will perform a mapReduce function to select active posts, group them by `user_name`, and count the number of posts by each user. - -```javascript -db.posts.mapReduce( - function() { emit(this.user_name, 1); }, - function(key, values) { return Array.sum(values); }, - { - query: { status: "active" }, - out: "post_total" - } -) -``` - -The above mapReduce query outputs the following result: - -```json -{ - "result" : "post_total", - "timeMillis" : 9, - "counts" : { - "input" : 4, - "emit" : 4, - "reduce" : 2, - "output" : 2 - }, - "ok" : 1 -} -``` - -To see the result of this mapReduce query, you can use the `find` operator: - -```javascript -db.post_total.find() -``` - -This query will return results showing the count of active posts for each user: - -```json -{ "_id" : "tom", "value" : 2 } -{ "_id" : "mark", "value" : 2 } -``` - -MapReduce queries in MongoDB are powerful for constructing complex aggregation queries using custom JavaScript functions, providing flexibility in data processing and analysis. - -### Diagram: MapReduce Process - -```mermaid -graph TD; - A[Query Collection] --> B(Map Function); - B --> C(Emit Key-Value Pairs); - C --> D(Reduce Function); - D --> E(Aggregated Results); -``` - -:::note Performance Considerations - -When using MapReduce in MongoDB: -- Consider the performance overhead, especially for large data sets. -- Optimize your map and reduce functions for efficiency. -- Utilize indexes to improve query performance. -::: - -### Table: MapReduce Options - -| Option | Description | -|--------|------------------------------------------------| -| out | Specifies the location of the query result. | -| query | Optional selection criteria for documents. | -| sort | Optional sort criteria. | -| limit | Optional maximum number of documents to return| diff --git a/docs/MongoDB/Advanced MongoDB/mongodb-regular-expression.md b/docs/MongoDB/Advanced MongoDB/mongodb-regular-expression.md deleted file mode 100644 index 56f2e9bcb..000000000 --- a/docs/MongoDB/Advanced MongoDB/mongodb-regular-expression.md +++ /dev/null @@ -1,65 +0,0 @@ ---- -id: mongodb-regular-expression -title: MongoDB - Regular Expression -sidebar_label: Regular Expression -sidebar_position: 11 -tags: [mongodb, regular expression, pattern matching] -description: Learn how to use regular expressions for pattern matching in MongoDB using the $regex operator. ---- - -Regular Expressions are commonly used in programming languages to search for patterns or words within strings. MongoDB supports regular expressions for string pattern matching using the $regex operator, based on PCRE (Perl Compatible Regular Expression) syntax. - -## Using Regular Expressions - -Assume we have a document in the `posts` collection: - -```javascript -db.posts.insert({ - "post_text": "enjoy the mongodb articles on tutorialspoint", - "tags": ["mongodb", "tutorialspoint"] -}) -``` - -To search for posts containing the string "tutorialspoint" in their `post_text` field using a regular expression: - -```javascript -db.posts.find({ post_text: { $regex: "tutorialspoint" } }).pretty() -``` - -### Diagram: Regular Expression Query Process - -```mermaid -graph LR; - A[Query Collection] --> B(Regex Pattern Matching); - B --> C(Retrieve Matching Documents); -``` - -### Note: Case Insensitive Search - -To perform a case-insensitive search, use the $options parameter with value "$i" in the regex query: - -```javascript -db.posts.find({ post_text: { $regex: "tutorialspoint", $options: "$i" } }) -``` - -### Using Regex for Array Elements - -Regular expressions can also be applied to array fields, such as searching for posts with tags starting from "tutorial": - -```javascript -db.posts.find({ tags: { $regex: "tutorial" } }) -``` - -### Optimizing Regex Queries - -- Indexed fields improve the performance of regular expression queries by using indexed values for matching. -- Prefix expressions in regular expressions, like "^tut," optimize searches by matching strings starting with specific characters. - -## Table: Regex Search Options - -| Option | Description | -|--------------|----------------------------------------------------------------| -| $regex | Operator for regular expression pattern matching. | -| $options | Optional parameter for regex options like case insensitivity. | -| ^ | Anchor for matching the start of a string. | -| $ | Anchor for matching the end of a string. | diff --git a/docs/MongoDB/Advanced MongoDB/mongodb-relationship.md b/docs/MongoDB/Advanced MongoDB/mongodb-relationship.md deleted file mode 100644 index e8312b954..000000000 --- a/docs/MongoDB/Advanced MongoDB/mongodb-relationship.md +++ /dev/null @@ -1,119 +0,0 @@ ---- -id: mongodb-relationship -title: MongoDB - Relationships -sidebar_label: Relationships -sidebar_position: 1 -tags: [mongodb, relationships, embedded, referenced] -description: Learn how to model relationships in MongoDB using embedded and referenced approaches. ---- - -# MongoDB - Relationships - -Relationships in MongoDB represent how various documents are logically related to each other. Relationships can be modeled via Embedded and Referenced approaches. Such relationships can be either 1:1, 1:N, N:1 or N:N. - -Let us consider the case of storing addresses for users. So, one user can have multiple addresses making this a 1:N relationship. - -Following is the sample document structure of user document − - -```json -{ - "_id":ObjectId("52ffc33cd85242f436000001"), - "name": "Tom Hanks", - "contact": "987654321", - "dob": "01-01-1991" -} -``` - -Following is the sample document structure of address document − - -```json -{ - "_id":ObjectId("52ffc4a5d85242602e000000"), - "building": "22 A, Indiana Apt", - "pincode": 123456, - "city": "Los Angeles", - "state": "California" -} -``` - -## Modeling Embedded Relationships - -In the embedded approach, we will embed the address document inside the user document. - -```mongodb -db.users.insert({ - { - "_id":ObjectId("52ffc33cd85242f436000001"), - "contact": "987654321", - "dob": "01-01-1991", - "name": "Tom Benzamin", - "address": [ - { - "building": "22 A, Indiana Apt", - "pincode": 123456, - "city": "Los Angeles", - "state": "California" - }, - { - "building": "170 A, Acropolis Apt", - "pincode": 456789, - "city": "Chicago", - "state": "Illinois" - } - ] - } -}) -``` - -This approach maintains all the related data in a single document, which makes it easy to retrieve and maintain. The whole document can be retrieved in a single query such as − - -```mongodb -db.users.findOne({"name":"Tom Benzamin"},{"address":1}) -``` - -Note that in the above query, `db` and `users` are the database and collection respectively. - -:::note -The drawback is that if the embedded document keeps on growing too much in size, it can impact the read/write performance. -::: - -## Modeling Referenced Relationships - -This is the approach of designing normalized relationships. In this approach, both the user and address documents will be maintained separately but the user document will contain a field that will reference the address document's `id` field. - -```json -{ - "_id":ObjectId("52ffc33cd85242f436000001"), - "contact": "987654321", - "dob": "01-01-1991", - "name": "Tom Benzamin", - "address_ids": [ - ObjectId("52ffc4a5d85242602e000000"), - ObjectId("52ffc4a5d85242602e000001") - ] -} -``` - -As shown above, the user document contains the array field `address_ids` which contains `ObjectIds` of corresponding addresses. Using these `ObjectIds`, we can query the address documents and get address details from there. With this approach, we will need two queries: first to fetch the `address_ids` fields from the user document and second to fetch these addresses from the address collection. - -```mongodb -var result = db.users.findOne({"name":"Tom Benzamin"},{"address_ids":1}) -var addresses = db.address.find({"_id":{"$in":result["address_ids"]}}) -``` - -## Diagram - -```mermaid -graph TD - A[User Document] -->|Embedded| B[Address Document] - A -->|Referenced| C[Address Document 1] - A -->|Referenced| D[Address Document 2] -``` - -## Summary Table - -| Approach | Description | Pros | Cons | -|----------|-------------|------|------| -| Embedded | Address documents are embedded within user documents | Easy retrieval, less complex queries | May lead to large documents, impacting performance | -| Referenced | User document references address documents via `ObjectIds` | Normalized data, avoids large documents | Requires multiple queries to retrieve related data | - diff --git a/docs/MongoDB/Advanced MongoDB/mongodb-text-search.md b/docs/MongoDB/Advanced MongoDB/mongodb-text-search.md deleted file mode 100644 index 39dd3636d..000000000 --- a/docs/MongoDB/Advanced MongoDB/mongodb-text-search.md +++ /dev/null @@ -1,86 +0,0 @@ ---- -id: mongodb-text-search -title: MongoDB - Text Search -sidebar_label: Text Search -sidebar_position: 10 -tags: [mongodb, text search, indexing] -description: Learn how to perform text search in MongoDB using text indexes to search inside string content efficiently. ---- - -Starting from version 2.4, MongoDB supports text indexes for searching inside string content. Text Search uses stemming techniques to search for specified words in string fields by dropping stemming stop words like "a," "an," "the," etc. MongoDB currently supports around 15 languages for text search. - -## Enabling Text Search - -Initially, Text Search was an experimental feature, but starting from version 2.6, it is enabled by default in MongoDB configurations. - -## Creating Text Index - -Consider the following documents in the `posts` collection: - -```javascript -db.posts.insert({ - "post_text": "enjoy the mongodb articles on tutorialspoint", - "tags": ["mongodb", "tutorialspoint"] -}) - -db.posts.insert({ - "post_text": "writing tutorials on mongodb", - "tags": ["mongodb", "tutorial"] -}) -``` - -To create a text index on the `post_text` field, enabling text search inside the posts' text: - -```javascript -db.posts.createIndex({ post_text: "text" }) -``` - -### Using Text Index - -After creating the text index on the `post_text` field, you can search for posts containing specific words using the `$text` operator: - -```javascript -db.posts.find({ $text: { $search: "tutorialspoint" } }).pretty() -``` - -This command retrieves documents that contain the word "tutorialspoint" in their post text. - -### Diagram: Text Search Process - -```mermaid -graph LR; - A[Query Collection] --> B(Text Indexing); - B --> C(Search using $text operator); - C --> D(Retrieve Matching Documents); -``` - -::: note: Performance Considerations - -When using text search in MongoDB: -- Text indexes can significantly improve search performance for string content. -- Consider the language-specific settings for stemming and stop words. -- Optimize text indexes based on the search requirements. -::: -### Table: Text Search Options - -| Option | Description | -|--------|--------------------------------------------------| -| $text | Operator for text search using text indexes. | -| $search| Specifies the search term or phrase. | -| $language| Optional parameter for specifying the language for text search. | - -## Deleting Text Index - -To delete an existing text index, first, find the name of the index using the `getIndexes` method: - -```javascript -db.posts.getIndexes() -``` - -After obtaining the index name, use the `dropIndex` method to delete the text index: - -```javascript -db.posts.dropIndex("post_text_text") -``` - -This command deletes the text index named "post_text_text" from the `posts` collection. diff --git a/docs/MongoDB/Advanced MongoDB/working-with-rockmorgo.md b/docs/MongoDB/Advanced MongoDB/working-with-rockmorgo.md deleted file mode 100644 index 3c2124b32..000000000 --- a/docs/MongoDB/Advanced MongoDB/working-with-rockmorgo.md +++ /dev/null @@ -1,70 +0,0 @@ ---- -id: working-with-rockmorgo -title: Working with RockMongo -sidebar_label: Working with RockMongo -sidebar_position: 12 -tags: [mongodb, RockMongo, administration, database management] -description: Learn how to work with RockMongo, a MongoDB administration tool, for managing databases, collections, documents, and more. ---- - -RockMongo is a powerful MongoDB administration tool that provides a user-friendly interface for managing MongoDB databases, collections, documents, and indexes. It is similar to PHPMyAdmin for PHP and MySQL. - -## Downloading and Installing RockMongo - -You can download the latest version of RockMongo from the [official GitHub repository](https://github.com/iwind/rockmongo). After downloading, follow these steps to install RockMongo: - -1. Unzip the downloaded package into your server's root folder. -2. Rename the extracted folder to "rockmongo." -3. Access RockMongo by opening any web browser and navigating to the `index.php` page in the `rockmongo` folder. -4. Log in using the default credentials: Username - admin, Password - admin. - -### Diagram: RockMongo Installation Process - -```mermaid -graph LR; - A[Download RockMongo] --> B(Unzip Package); - B --> C(Rename Folder to RockMongo); - C --> D(Access index.php in Browser); - D --> E(Login with Default Credentials); -``` - -:::note Default Credentials - -Upon installation, RockMongo uses default credentials (Username: admin, Password: admin). Change these credentials for security purposes. - -::: -## Basic Operations with RockMongo - -Let's explore some basic operations you can perform with RockMongo: - -### Creating New Database - -1. Click on the "Databases" tab. -2. Click "Create New Database." -3. Enter the new database name and click "Create." - -### Creating New Collection - -1. Select the desired database from the left panel. -2. Click "New Collection" at the top. -3. Provide the collection name and click "Create." - -### Creating New Document - -1. Navigate to the collection where you want to add documents. -2. Click "Insert" at the top. -3. Enter the document's data in JSON or array format and click "Save." - -### Export/Import Data - -1. Select a collection. -2. Click "Export/Import" at the top to export or import data in zip format. - -## Table: RockMongo Operations Overview - -| Operation | Description | -|---------------------|---------------------------------------------------------| -| Create New Database | Add a new database to the MongoDB server. | -| Create New Collection| Create a new collection within a database. | -| Create New Document | Add a new document to a collection. | -| Export/Import Data | Transfer data in and out of collections in zip format. | diff --git a/docs/MongoDB/_category.json b/docs/MongoDB/_category.json deleted file mode 100644 index e959a3e82..000000000 --- a/docs/MongoDB/_category.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "label": "MongoDB", - "position": 16, - "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-collection.md b/docs/MongoDB/create-collection.md deleted file mode 100644 index 296934de5..000000000 --- a/docs/MongoDB/create-collection.md +++ /dev/null @@ -1,112 +0,0 @@ ---- -id: mongodb-create-collection -title: MongoDB - Create Collection -sidebar_label: Create Collection -sidebar_position: 8 -tags: [mongodb, create collection, commands] -description: Learn how to create a collection in MongoDB using the createCollection() method, along with examples, options, and additional commands. ---- - -# MongoDB - Create Collection - -In this chapter, we will see how to create a collection using MongoDB. - -## The `createCollection()` Method - -MongoDB `db.createCollection(name, options)` is used to create a collection. - -### Syntax - -The basic syntax of the `createCollection()` command is as follows: - -```sql -db.createCollection(name, options) -``` - -In the command, `name` is the name of the collection to be created. `Options` is a document and is used to specify the configuration of the collection. - -### Parameters - -| Parameter | Type | Description | -|-----------|--------|------------------------------------------------------------------| -| name | String | Name of the collection to be created | -| options | Document | (Optional) Specify options about memory size and indexing | - -The `options` parameter is optional, so you need to specify only the name of the collection. Following is the list of options you can use: - -### Options - -| Field | Type | Description | -|---------------|---------|--------------------------------------------------------------------------------------------------------------------| -| capped | Boolean | (Optional) If true, enables a capped collection. Capped collection is a fixed size collection that automatically overwrites its oldest entries when it reaches its maximum size. If you specify true, you need to specify the `size` parameter also. | -| autoIndexId | Boolean | (Optional) If true, automatically creates an index on the `_id` field. Default value is false. | -| size | Number | (Optional) Specifies a maximum size in bytes for a capped collection. If capped is true, then you need to specify this field also. | -| max | Number | (Optional) Specifies the maximum number of documents allowed in the capped collection. | - -While inserting the document, MongoDB first checks the `size` field of the capped collection, then it checks the `max` field. - -### Examples - -The basic syntax of the `createCollection()` method without options is as follows: - -```bash -> use test -switched to db test -> db.createCollection("mycollection") -{ "ok" : 1 } -``` - -You can check the created collection by using the command `show collections`. - -```bash -> show collections -mycollection -system.indexes -``` - -The following example shows the syntax of the `createCollection()` method with a few important options: - -```bash -> db.createCollection("mycol", { capped: true, autoIndexId: true, size: 6142800, max: 10000 }) -{ - "ok" : 0, - "errmsg" : "BSON field 'create.autoIndexId' is an unknown field.", - "code" : 40415, - "codeName" : "Location40415" -} -``` - -In MongoDB, you don't need to create a collection explicitly. MongoDB creates the collection automatically when you insert some document. - -```bash -> db.tutorialspoint.insert({"name" : "tutorialspoint"}) -WriteResult({ "nInserted" : 1 }) -> show collections -mycol -mycollection -system.indexes -tutorialspoint -``` - -## Collection Creation Diagram - -```mermaid -graph TD - A[Create Collection] --> B[createCollection Method] - B --> C[Syntax] - B --> D[Parameters] - D --> E[name] - D --> F[options] - C --> G[Example without options] - C --> H[Example with options] - H --> I[Insert Document] - I --> J[Check Collections] -``` - -## Command Summary - -| Command | Description | -|--------------------------------------------|-----------------------------------------------------------------------------| -| `db.createCollection(name, options)` | Create a collection with the specified name and options | -| `show collections` | List all collections in the current database | -| `db.collection.insert(document)` | Insert a document into a collection, creating the collection if it does not exist | diff --git a/docs/MongoDB/create-database.md b/docs/MongoDB/create-database.md deleted file mode 100644 index a5bc228db..000000000 --- a/docs/MongoDB/create-database.md +++ /dev/null @@ -1,83 +0,0 @@ ---- -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 deleted file mode 100644 index 3e12fd305..000000000 --- a/docs/MongoDB/data-modeling.md +++ /dev/null @@ -1,168 +0,0 @@ ---- -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/datatypes.md b/docs/MongoDB/datatypes.md deleted file mode 100644 index 300ad46cc..000000000 --- a/docs/MongoDB/datatypes.md +++ /dev/null @@ -1,53 +0,0 @@ ---- -id: mongodb-datatypes -title: MongoDB - Datatypes -sidebar_label: Datatypes -sidebar_position: 10 -tags: [mongodb, datatypes, commands] -description: Learn about the various datatypes supported by MongoDB, their uses, and examples. ---- - -# MongoDB - Datatypes - -MongoDB supports many datatypes. Some of them are listed below: - - -| Datatype | Description | -|--------------------|-----------------------------------------------------------------------------| -| **String** | Stores UTF-8 valid strings. | -| **Integer** | Stores 32-bit or 64-bit numerical values. | -| **Boolean** | Stores a boolean value (true/false). | -| **Double** | Stores floating-point values. | -| **Min/Max Keys** | Used to compare values against the lowest and highest BSON elements. | -| **Arrays** | Stores arrays or lists of multiple values. | -| **Timestamp** | Stores timestamps, useful for recording modification or addition times. | -| **Object** | Used for embedded documents. | -| **Null** | Stores a Null value. | -| **Symbol** | Used identically to a string, reserved for specific languages. | -| **Date** | Stores the current date/time in UNIX format. | -| **Object ID** | Stores the document’s ID. | -| **Binary Data** | Stores binary data. | -| **Code** | Stores JavaScript code in the document. | -| **Regular Expression** | Stores regular expressions. | - - -## Datatype Diagram - -```mermaid -graph TD - A[Datatypes] --> B[String] - A --> C[Integer] - A --> D[Boolean] - A --> E[Double] - A --> F[Min/Max Keys] - A --> G[Arrays] - A --> H[Timestamp] - A --> I[Object] - A --> J[Null] - A --> K[Symbol] - A --> L[Date] - A --> M[Object ID] - A --> N[Binary Data] - A --> O[Code] - A --> P[Regular Expression] -``` diff --git a/docs/MongoDB/delete-document.md b/docs/MongoDB/delete-document.md deleted file mode 100644 index 53b71da96..000000000 --- a/docs/MongoDB/delete-document.md +++ /dev/null @@ -1,98 +0,0 @@ ---- -id: mongodb-delete-document -title: delete Document -sidebar_label: Delete Document -sidebar_position: 14 -tags: [mongodb, delete, document, commands] -description: Learn how to Delete documents in MongoDB collections using different methods. ---- - -# MongoDB - Delete Document - -In this chapter, we will learn how to delete a document using MongoDB. - -## The remove() Method - -MongoDB's `remove()` method is used to remove a document from the collection. The `remove()` method accepts two parameters: one is the deletion criteria and the second is the `justOne` flag. - -- **deletion criteria** − (Optional) The criteria according to which documents will be removed. -- **justOne** − (Optional) If set to `true` or `1`, then only one document will be removed. - -### Syntax - -The basic syntax of the `remove()` method is as follows: - -```bash -> db.COLLECTION_NAME.remove(DELETION_CRITERIA) -``` - -### Example - -Consider the `mycol` collection has the following data: - -```json -{ "_id" : ObjectId("507f191e810c19729de860e1"), "title": "MongoDB Overview" }, -{ "_id" : ObjectId("507f191e810c19729de860e2"), "title": "NoSQL Overview" }, -{ "_id" : ObjectId("507f191e810c19729de860e3"), "title": "Tutorials Point Overview" } -``` - -Following example will remove all the documents whose title is 'MongoDB Overview'. - -```bash -> db.mycol.remove({'title':'MongoDB Overview'}) -WriteResult({ "nRemoved" : 1 }) -> db.mycol.find() -{ "_id" : ObjectId("507f191e810c19729de860e2"), "title": "NoSQL Overview" } -{ "_id" : ObjectId("507f191e810c19729de860e3"), "title": "Tutorials Point Overview" } -``` - -### Remove Only One - -If there are multiple records and you want to delete only the first record, then set the `justOne` parameter in the `remove()` method. - -```bash -> db.COLLECTION_NAME.remove(DELETION_CRITERIA, 1) -``` - -### Remove All Documents - -If you don't specify deletion criteria, then MongoDB will delete all documents from the collection. This is equivalent to SQL's `TRUNCATE` command. - -```bash -> db.mycol.remove({}) -WriteResult({ "nRemoved" : 2 }) -> db.mycol.find() -``` - -## Diagrams - -### Remove Document Flow -```mermaid -graph TD; - A[Start] --> B[Specify Collection] - B --> C{Set Deletion Criteria?} - C -->|Yes| D[Specify Criteria] - C -->|No| E[Proceed Without Criteria] - D --> F{Set justOne Flag?} - F -->|Yes| G[Set justOne to true/1] - F -->|No| H[Set justOne to false/0] - G --> I[Execute remove method] - H --> I[Execute remove method] - E --> I[Execute remove method] - I --> J[Documents Deleted] - J --> K[End] -``` - -## Notes - -- Always double-check your deletion criteria to avoid accidental removal of unintended documents. -- Use `justOne` flag to limit deletion to a single document if needed. -- Omitting the deletion criteria will result in removing all documents from the collection. - -## Table of Commands - -| Command | Description | -| ------- | ----------- | -| `db.COLLECTION_NAME.remove(DELETION_CRITERIA)` | Removes documents matching the criteria. | -| `db.COLLECTION_NAME.remove(DELETION_CRITERIA, 1)` | Removes only the first document matching the criteria. | -| `db.COLLECTION_NAME.remove({})` | Removes all documents from the collection. | diff --git a/docs/MongoDB/drop-collection.md b/docs/MongoDB/drop-collection.md deleted file mode 100644 index 23e25ce2f..000000000 --- a/docs/MongoDB/drop-collection.md +++ /dev/null @@ -1,76 +0,0 @@ ---- -id: mongodb-drop-collection -title: MongoDB - Drop Collection -sidebar_label: Drop Collection -sidebar_position: 9 -tags: [mongodb, drop collection, commands] -description: Learn how to drop a collection in MongoDB using the drop() method, along with examples, additional commands, and a detailed diagram. ---- - -# MongoDB - Drop Collection - -In this chapter, we will see how to drop a collection using MongoDB. - -## The `drop()` Method - -MongoDB's `db.collection.drop()` is used to drop a collection from the database. - -### Syntax - -The basic syntax of the `drop()` command is as follows: - -```sql -db.COLLECTION_NAME.drop() -``` - -### Example - -First, check the available collections in your database `mydb`. - -```bash -> use mydb -switched to db mydb -> show collections -mycol -mycollection -system.indexes -tutorialspoint -``` - -Now drop the collection with the name `mycollection`. - -```bash -> db.mycollection.drop() -true -``` - -Again, check the list of collections in the database. - -```bash -> show collections -mycol -system.indexes -tutorialspoint -``` - -The `drop()` method will return `true` if the selected collection is dropped successfully; otherwise, it will return `false`. - -## Drop Collection Diagram - -```mermaid -graph TD - A[Drop Collection] --> B[drop Method] - B --> C[Syntax] - B --> D[Example] - D --> E[Check Collections] - E --> F[Drop Collection] - F --> G[Verify Collection Dropped] -``` - -## Command Summary - -| Command | Description | -|-------------------------------|------------------------------------------------------| -| `db.COLLECTION_NAME.drop()` | Drop the specified collection from the database | -| `show collections` | List all collections in the current database | -| `use DATABASE_NAME` | Switch to the specified database | diff --git a/docs/MongoDB/drop-database.md b/docs/MongoDB/drop-database.md deleted file mode 100644 index 262a1ebd5..000000000 --- a/docs/MongoDB/drop-database.md +++ /dev/null @@ -1,75 +0,0 @@ ---- -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 deleted file mode 100644 index 526834232..000000000 --- a/docs/MongoDB/home.md +++ /dev/null @@ -1,20 +0,0 @@ ---- -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/insert-document.md b/docs/MongoDB/insert-document.md deleted file mode 100644 index ec858ddd0..000000000 --- a/docs/MongoDB/insert-document.md +++ /dev/null @@ -1,180 +0,0 @@ ---- -id: mongodb-insert-document -title: MongoDB - Insert Document -sidebar_label: Insert Document -sidebar_position: 11 -tags: [mongodb, insert, document, commands] -description: Learn how to insert documents into MongoDB collections using different methods. ---- - -# MongoDB - Insert Document - -In this chapter, we will learn how to insert documents in MongoDB collections. - -## The insert() Method - -To insert data into a MongoDB collection, you can use MongoDB's `insert()` or `save()` method. - -### Syntax - -The basic syntax of the `insert()` command is as follows: - -```javascript -db.COLLECTION_NAME.insert(document) -``` - -### Example - -```javascript -> db.users.insert({ -... _id : ObjectId("507f191e810c19729de860ea"), -... title: "MongoDB Overview", -... description: "MongoDB is no SQL database", -... by: "tutorials point", -... url: "http://www.tutorialspoint.com", -... tags: ['mongodb', 'database', 'NoSQL'], -... likes: 100 -... }) -WriteResult({ "nInserted" : 1 }) -> -``` - -In the inserted document, if you don't specify the `_id` parameter, MongoDB assigns a unique ObjectId for this document. - -### ObjectId Structure - -```mermaid -graph TD - A[ObjectId] --> B[4 bytes timestamp] - A --> C[3 bytes machine id] - A --> D[2 bytes process id] - A --> E[3 bytes incrementer] -``` - -### Inserting Multiple Documents - -You can also pass an array of documents into the `insert()` method. - -```javascript -> db.createCollection("post") -> db.post.insert([ - { - title: "MongoDB Overview", - description: "MongoDB is no SQL database", - by: "tutorials point", - url: "http://www.tutorialspoint.com", - tags: ["mongodb", "database", "NoSQL"], - likes: 100 - }, - { - title: "NoSQL Database", - description: "NoSQL database doesn't have tables", - by: "tutorials point", - url: "http://www.tutorialspoint.com", - tags: ["mongodb", "database", "NoSQL"], - likes: 20, - comments: [ - { - user: "user1", - message: "My first comment", - dateCreated: new Date(2013, 11, 10, 2, 35), - like: 0 - } - ] - } -]) -BulkWriteResult({ - "writeErrors" : [ ], - "writeConcernErrors" : [ ], - "nInserted" : 2, - "nUpserted" : 0, - "nMatched" : 0, - "nModified" : 0, - "nRemoved" : 0, - "upserted" : [ ] -}) -> -``` - -## The insertOne() Method - -If you need to insert only one document into a collection, you can use this method. - -### Syntax - -The basic syntax of the `insertOne()` command is as follows: - -```javascript -db.COLLECTION_NAME.insertOne(document) -``` - -### Example - -```javascript -> db.createCollection("empDetails") -{ "ok" : 1 } -> db.empDetails.insertOne( - { - First_Name: "Radhika", - Last_Name: "Sharma", - Date_Of_Birth: "1995-09-26", - e_mail: "radhika_sharma.123@gmail.com", - phone: "9848022338" - }) -{ - "acknowledged" : true, - "insertedId" : ObjectId("5dd62b4070fb13eec3963bea") -} -> -``` - -## The insertMany() Method - -You can insert multiple documents using the `insertMany()` method. To this method, you need to pass an array of documents. - -### Example - -```javascript -> db.empDetails.insertMany( - [ - { - First_Name: "Radhika", - Last_Name: "Sharma", - Date_Of_Birth: "1995-09-26", - e_mail: "radhika_sharma.123@gmail.com", - phone: "9000012345" - }, - { - First_Name: "Rachel", - Last_Name: "Christopher", - Date_Of_Birth: "1990-02-16", - e_mail: "Rachel_Christopher.123@gmail.com", - phone: "9000054321" - }, - { - First_Name: "Fathima", - Last_Name: "Sheik", - Date_Of_Birth: "1990-02-16", - e_mail: "Fathima_Sheik.123@gmail.com", - phone: "9000054321" - } - ] -) -{ - "acknowledged" : true, - "insertedIds" : [ - ObjectId("5dd631f270fb13eec3963bed"), - ObjectId("5dd631f270fb13eec3963bee"), - ObjectId("5dd631f270fb13eec3963bef") - ] -} -> -``` - -## Summary Table - -| Method | Description | -|---------------|-----------------------------------------| -| **insert()** | Inserts one or multiple documents | -| **insertOne()** | Inserts a single document | -| **insertMany()** | Inserts multiple documents | diff --git a/docs/MongoDB/mongodb-advantages.md b/docs/MongoDB/mongodb-advantages.md deleted file mode 100644 index 398db130d..000000000 --- a/docs/MongoDB/mongodb-advantages.md +++ /dev/null @@ -1,65 +0,0 @@ ---- -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-aggregation.md b/docs/MongoDB/mongodb-aggregation.md deleted file mode 100644 index 69906462e..000000000 --- a/docs/MongoDB/mongodb-aggregation.md +++ /dev/null @@ -1,89 +0,0 @@ ---- -id: mongodb-aggregation -title: MongoDB - Aggregation -sidebar_label: Aggregation -sidebar_position: 19 -tags: [mongodb, aggregation, database, operations] -description: Learn how to perform aggregation operations in MongoDB to process and compute data results. ---- - -# MongoDB - Aggregation - -Aggregation operations in MongoDB process data records and return computed results. These operations group values from multiple documents together and can perform a variety of operations on the grouped data to return a single result. - -## The aggregate() Method - -For aggregation in MongoDB, you should use the `aggregate()` method. - -### Syntax - -The basic syntax of the `aggregate()` method is as follows: - -```shell ->db.COLLECTION_NAME.aggregate(AGGREGATE_OPERATION) -``` - -### Example - -In the collection, you have the following data: - -```json -[ - { - "_id": ObjectId("7df78ad8902c"), - "title": "MongoDB Overview", - "description": "MongoDB is a NoSQL database", - "by_user": "tutorials point", - "url": "http://www.tutorialspoint.com", - "tags": ["mongodb", "database", "NoSQL"], - "likes": 100 - }, - { - "_id": ObjectId("7df78ad8902d"), - "title": "NoSQL Overview", - "description": "NoSQL database is very fast", - "by_user": "tutorials point", - "url": "http://www.tutorialspoint.com", - "tags": ["mongodb", "database", "NoSQL"], - "likes": 10 - }, - { - "_id": ObjectId("7df78ad8902e"), - "title": "Neo4j Overview", - "description": "Neo4j is a NoSQL database", - "by_user": "Neo4j", - "url": "http://www.neo4j.com", - "tags": ["neo4j", "database", "NoSQL"], - "likes": 750 - } -] -``` - -Now, from the above collection, if you want to display a list stating how many tutorials are written by each user, then you will use the following `aggregate()` method: - -```shell -> db.mycol.aggregate([{$group : {_id : "$by_user", num_tutorial : {$sum : 1}}}]) -{ "_id" : "tutorials point", "num_tutorial" : 2 } -{ "_id" : "Neo4j", "num_tutorial" : 1 } -``` - -In the above example, we have grouped documents by the field `by_user` and counted the number of tutorials written by each user. - -## Aggregation Expressions - -Here are some common aggregation expressions used with the `aggregate()` method: - -| Expression | Description | Example | -|------------|-------------|---------| -| $sum | Sums up the defined value from all documents in the collection. | `db.mycol.aggregate([{$group : {_id : "$by_user", num_tutorial : {$sum : "$likes"}}}])` | -| $avg | Calculates the average of all given values from all documents in the collection. | `db.mycol.aggregate([{$group : {_id : "$by_user", num_tutorial : {$avg : "$likes"}}}])` | -| $min | Gets the minimum of the corresponding values from all documents in the collection. | `db.mycol.aggregate([{$group : {_id : "$by_user", num_tutorial : {$min : "$likes"}}}])` | -| $max | Gets the maximum of the corresponding values from all documents in the collection. | `db.mycol.aggregate([{$group : {_id : "$by_user", num_tutorial : {$max : "$likes"}}}])` | -| $push | Inserts the value into an array in the resulting document. | `db.mycol.aggregate([{$group : {_id : "$by_user", url : {$push: "$url"}}}])` | -| $addToSet | Inserts the value into an array in the resulting document but does not create duplicates. | `db.mycol.aggregate([{$group : {_id : "$by_user", url : {$addToSet : "$url"}}}])` | -| $first | Gets the first document from the source documents according to the grouping. | `db.mycol.aggregate([{$group : {_id : "$by_user", first_url : {$first : "$url"}}}])` | -| $last | Gets the last document from the source documents according to the grouping. | `db.mycol.aggregate([{$group : {_id : "$by_user", last_url : {$last : "$url"}}}])` | - -## Pipeline Concept - -MongoDB supports the pipeline concept in the aggregation framework, similar to UNIX command shell pipelines. The pipeline allows executing operations on input data \ No newline at end of file diff --git a/docs/MongoDB/mongodb-create-backup.md b/docs/MongoDB/mongodb-create-backup.md deleted file mode 100644 index 0d8759b7f..000000000 --- a/docs/MongoDB/mongodb-create-backup.md +++ /dev/null @@ -1,88 +0,0 @@ ---- -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 deleted file mode 100644 index cb62aaf51..000000000 --- a/docs/MongoDB/mongodb-deployment.md +++ /dev/null @@ -1,89 +0,0 @@ ---- -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-environment.md b/docs/MongoDB/mongodb-environment.md deleted file mode 100644 index 92b0be04e..000000000 --- a/docs/MongoDB/mongodb-environment.md +++ /dev/null @@ -1,152 +0,0 @@ ---- -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/mongodb-indexing.md b/docs/MongoDB/mongodb-indexing.md deleted file mode 100644 index a7d923f50..000000000 --- a/docs/MongoDB/mongodb-indexing.md +++ /dev/null @@ -1,180 +0,0 @@ ---- -id: mongodb-indexing -title: MongoDB - Indexing -sidebar_label: Indexing -sidebar_position: 18 -tags: [mongodb, indexing, database, commands] -description: Learn how to create and manage indexes in MongoDB to improve query performance. ---- - -# MongoDB - Indexing - -Indexes support the efficient resolution of queries. Without indexes, MongoDB must scan every document of a collection to select those documents that match the query statement. This scan is highly inefficient and requires MongoDB to process a large volume of data. - -Indexes are special data structures that store a small portion of the data set in an easy-to-traverse form. The index stores the value of a specific field or set of fields, ordered by the value of the field as specified in the index. - -## The createIndex() Method - -To create an index, you need to use the `createIndex()` method of MongoDB. - -### Syntax - -The basic syntax of the `createIndex()` method is as follows: - -```shell ->db.COLLECTION_NAME.createIndex({KEY:1}) -``` - -Here, `KEY` is the name of the field on which you want to create an index, and `1` is for ascending order. To create an index in descending order, you need to use `-1`. - -### Example - -```shell ->db.mycol.createIndex({"title":1}) -{ - "createdCollectionAutomatically" : false, - "numIndexesBefore" : 1, - "numIndexesAfter" : 2, - "ok" : 1 -} -``` - -In the `createIndex()` method, you can pass multiple fields to create an index on multiple fields. - -```shell ->db.mycol.createIndex({"title":1,"description":-1}) -``` - -## Index Options - -This method also accepts a list of options (which are optional). Following is the list: - -| Parameter | Type | Description | -|---------------------|----------|-----------------------------------------------------------------------------------------------------------------------------------| -| background | Boolean | Builds the index in the background so that building an index does not block other database activities. Default value is `false`. | -| unique | Boolean | Creates a unique index so that the collection will not accept insertion of documents where the index key matches an existing value. Specify `true` to create a unique index. Default value is `false`. | -| name | String | The name of the index. If unspecified, MongoDB generates an index name by concatenating the names of the indexed fields and the sort order. | -| sparse | Boolean | If `true`, the index only references documents with the specified field. These indexes use less space but behave differently in some situations (particularly sorts). Default value is `false`. | -| expireAfterSeconds | Integer | Specifies a value, in seconds, as a TTL to control how long MongoDB retains documents in this collection. | -| weights | Document | The weight is a number ranging from 1 to 99,999 and denotes the significance of the field relative to other indexed fields in terms of the score. | -| default_language | String | For a text index, the language that determines the list of stop words and the rules for the stemmer and tokenizer. Default value is `English`. | -| language_override | String | For a text index, specify the name of the field in the document that contains the language to override the default language. Default value is `language`. | - -## The dropIndex() Method - -You can drop a particular index using the `dropIndex()` method of MongoDB. - -### Syntax - -The basic syntax of the `dropIndex()` method is as follows: - -```shell ->db.COLLECTION_NAME.dropIndex({KEY:1}) -``` - -Here, `KEY` is the name of the field on which you want to remove an existing index. Instead of the index specification document (above syntax), you can also specify the name of the index directly as: - -```shell -dropIndex("name_of_the_index") -``` - -### Example - -```shell -> db.mycol.dropIndex({"title":1}) -{ - "ok" : 0, - "errmsg" : "can't find index with key: { title: 1.0 }", - "code" : 27, - "codeName" : "IndexNotFound" -} -``` - -## The dropIndexes() Method - -This method deletes multiple (specified) indexes on a collection. - -### Syntax - -The basic syntax of the `dropIndexes()` method is as follows: - -```shell ->db.COLLECTION_NAME.dropIndexes() -``` - -### Example - -Assume we have created 2 indexes in the named `mycol` collection as shown below: - -```shell -> db.mycol.createIndex({"title":1,"description":-1}) -``` - -Following example removes the above-created indexes of `mycol`: - -```shell ->db.mycol.dropIndexes({"title":1,"description":-1}) -{ "nIndexesWas" : 2, "ok" : 1 } -``` - -## The getIndexes() Method - -This method returns the description of all the indexes in the collection. - -### Syntax - -Following is the basic syntax of the `getIndexes()` method: - -```shell -db.COLLECTION_NAME.getIndexes() -``` - -### Example - -Assume we have created 2 indexes in the named `mycol` collection as shown below: - -```shell -> db.mycol.createIndex({"title":1,"description":-1}) -``` - -Following example retrieves all the indexes in the collection `mycol`: - -```shell -> db.mycol.getIndexes() -[ - { - "v" : 2, - "key" : { - "_id" : 1 - }, - "name" : "_id_", - "ns" : "test.mycol" - }, - { - "v" : 2, - "key" : { - "title" : 1, - "description" : -1 - }, - "name" : "title_1_description_-1", - "ns" : "test.mycol" - } -] -``` - -## Diagram - -```mermaid -graph TD; - A["Start"] --> B["Specify Collection"] - B --> C{"Create Index"} - C -->|Single Field| D["createIndex({KEY:1})"] - C -->|Multiple Fields| E["createIndex({KEY1:1, KEY2:-1})"] - D --> F["Index Created"] - E --> F["Index Created"] - F --> G["Use Index in Queries"] - G --> H["End"] -``` - -## Note -> Indexes can greatly improve query performance, but they also come with overhead. It's important to balance the benefits of indexing with the cost of maintaining them, especially for write-heavy operations. diff --git a/docs/MongoDB/mongodb-java-operations.md b/docs/MongoDB/mongodb-java-operations.md deleted file mode 100644 index 2dae88aee..000000000 --- a/docs/MongoDB/mongodb-java-operations.md +++ /dev/null @@ -1,457 +0,0 @@ ---- -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-limit-records.md b/docs/MongoDB/mongodb-limit-records.md deleted file mode 100644 index cfcf06468..000000000 --- a/docs/MongoDB/mongodb-limit-records.md +++ /dev/null @@ -1,99 +0,0 @@ ---- -id: mongodb-limit-records -title: MongoDB - Limit Records -sidebar_label: Limit Records -sidebar_position: 16 -tags: [mongodb, limit, records, commands] -description: Learn how to limit the number of records returned in a MongoDB query using the limit() method. ---- - -# MongoDB - Limit Records - -In this chapter, we will learn how to limit records using MongoDB. - -## The limit() Method - -To limit the records in MongoDB, you need to use the `limit()` method. The method accepts one number type argument, which is the number of documents that you want to be displayed. - -### Syntax - -The basic syntax of the `limit()` method is as follows: - -```bash -> db.COLLECTION_NAME.find().limit(NUMBER) -``` - -### Example - -Consider the collection `mycol` has the following data: - -```json -{ "_id" : ObjectId("507f191e810c19729de860e1"), "title": "MongoDB Overview" } -{ "_id" : ObjectId("507f191e810c19729de860e2"), "title": "NoSQL Overview" } -{ "_id" : ObjectId("507f191e810c19729de860e3"), "title": "Tutorials Point Overview" } -``` - -The following example will display only two documents while querying the document: - -```bash -> db.mycol.find({},{"title":1,_id:0}).limit(2) -{"title":"MongoDB Overview"} -{"title":"NoSQL Overview"} -``` - -If you don't specify the number argument in the `limit()` method, it will display all documents from the collection. - -## MongoDB skip() Method - -Apart from the `limit()` method, there is one more method `skip()` which also accepts a number type argument and is used to skip the number of documents. - -### Syntax - -The basic syntax of the `skip()` method is as follows: - -```bash -> db.COLLECTION_NAME.find().limit(NUMBER).skip(NUMBER) -``` - -### Example - -The following example will display only the second document: - -```bash -> db.mycol.find({},{"title":1,_id:0}).limit(1).skip(1) -{"title":"NoSQL Overview"} -``` - -Please note, the default value in the `skip()` method is 0. - -## Diagram - -### Limit and Skip Operation Flow -```mermaid -graph TD; - A[Start] --> B[Specify Collection] - B --> C{Set Limit} - C -->|Yes| D[Apply limit Method] - D --> E{Set Skip} - E -->|Yes| F[Apply skip Method] - E -->|No| G[Execute find with Limit] - F --> G[Execute find with Limit and Skip] - G --> H[Display Results] - H --> I[End] -``` - -## Notes - -> - The `limit()` method is used to restrict the number of documents returned in the query result. -> - The `skip()` method is used to skip a specified number of documents in the query result. -> - Combining `limit()` and `skip()` allows for pagination of results. -> - The default value for `skip()` is 0, meaning no documents are skipped. - -## Table of Commands - -| Command | Description | -| ------- | ----------- | -| `db.COLLECTION_NAME.find().limit(NUMBER)` | Limits the number of documents returned. | -| `db.COLLECTION_NAME.find().limit(NUMBER).skip(NUMBER)` | Limits and skips the number of documents returned. | -| `db.COLLECTION_NAME.find({}, {"title": 1, "_id": 0}).limit(2)` | Retrieves two documents with only the `title` field. | -| `db.COLLECTION_NAME.find({}, {"title": 1, "_id": 0}).limit(1).skip(1)` | Retrieves the second document with only the `title` field. | diff --git a/docs/MongoDB/mongodb-php.md b/docs/MongoDB/mongodb-php.md deleted file mode 100644 index 13ed0cf18..000000000 --- a/docs/MongoDB/mongodb-php.md +++ /dev/null @@ -1,258 +0,0 @@ ---- -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-projection.md b/docs/MongoDB/mongodb-projection.md deleted file mode 100644 index 3a8b9b6b5..000000000 --- a/docs/MongoDB/mongodb-projection.md +++ /dev/null @@ -1,73 +0,0 @@ ---- -id: mongodb-projection -title: MongoDB - Projection -sidebar_label: Projection -sidebar_position: 15 -tags: [mongodb, projection, document, commands] -description: Learn how to select only necessary fields from documents in MongoDB collections using projection. ---- - -# MongoDB - Projection - -In MongoDB, projection means selecting only the necessary data rather than selecting the whole data of a document. If a document has 5 fields and you need to show only 3, then select only those 3 fields. - -## The find() Method - -MongoDB's `find()` method, explained in MongoDB Query Document, accepts a second optional parameter that is a list of fields that you want to retrieve. In MongoDB, when you execute the `find()` method, it displays all fields of a document. To limit this, you need to set a list of fields with value 1 or 0. `1` is used to show the field while `0` is used to hide the fields. - -### Syntax - -The basic syntax of the `find()` method with projection is as follows: - -```bash -> db.COLLECTION_NAME.find({},{KEY:1}) -``` - -### Example - -Consider the collection `mycol` has the following data: - -```json -{ "_id" : ObjectId("507f191e810c19729de860e1"), "title": "MongoDB Overview" } -{ "_id" : ObjectId("507f191e810c19729de860e2"), "title": "NoSQL Overview" } -{ "_id" : ObjectId("507f191e810c19729de860e3"), "title": "Tutorials Point Overview" } -``` - -The following example will display the title of the document while querying the document: - -```bash -> db.mycol.find({},{"title":1,_id:0}) -{"title":"MongoDB Overview"} -{"title":"NoSQL Overview"} -{"title":"Tutorials Point Overview"} -``` - -Please note that the `_id` field is always displayed while executing the `find()` method. If you don't want this field, then you need to set it as `0`. - -## Diagrams - -### Projection Operation Flow -```mermaid -graph TD; - A[Start] --> B[Specify Collection] - B --> C{Set Projection Criteria} - C -->|Include Fields| D[Set Field to 1] - C -->|Exclude Fields| E[Set Field to 0] - D --> F[Execute find with Projection] - E --> F[Execute find with Projection] - F --> G[Display Results] - G --> H[End] -``` - -> **Notes:** -> - Projections are used to retrieve only the necessary data, reducing the amount of data transferred and improving query performance. -> - The `_id` field is included by default in projections. To exclude it, explicitly set `_id: 0`. -> - Use `1` to include a field in the projection and `0` to exclude it. - -## Table of Commands - -| Command | Description | -| ------- | ----------- | -| `db.COLLECTION_NAME.find({}, {KEY: 1})` | Includes specified fields in the results. | -| `db.COLLECTION_NAME.find({}, {KEY: 0})` | Excludes specified fields from the results. | -| `db.COLLECTION_NAME.find({}, {"title": 1, "_id": 0})` | Retrieves only the `title` field, excluding the `_id` field. | diff --git a/docs/MongoDB/mongodb-replication.md b/docs/MongoDB/mongodb-replication.md deleted file mode 100644 index 54a5fa832..000000000 --- a/docs/MongoDB/mongodb-replication.md +++ /dev/null @@ -1,86 +0,0 @@ ---- -id: mongodb-replication -title: MongoDB - Replication -sidebar_label: Replication -sidebar_position: 20 -tags: [mongodb, replication, database, replica set] -description: Learn about MongoDB replication, its benefits, how it works, and how to set up and manage replica sets. ---- - -# MongoDB - Replication - -Replication in MongoDB is the process of synchronizing data across multiple servers. It provides redundancy, increases data availability, and allows for disaster recovery and high availability of data. - -## Why Replication? - -- **Data Safety**: Keeps your data safe with multiple copies. -- **High Availability**: Ensures 24/7 availability of data. -- **Disaster Recovery**: Helps in recovering from disasters. -- **No Downtime**: No downtime for maintenance activities. -- **Read Scaling**: Provides extra copies for reading operations. -- **Transparent to Application**: Replica set is transparent to applications. - -## How Replication Works in MongoDB - -MongoDB achieves replication through the use of a replica set, which is a group of mongod instances hosting the same data set. Here's how it works: - -```mermaid -graph TD; - A[Client Application] --> B[Primary Node] - B -->|Replicates data| C[Secondary Node 1] - B -->|Replicates data| D[Secondary Node 2] - B -->|Replicates data| E[Secondary Node N] - C --> F[Automatic Failover] - D --> F - E --> F - F --> G[Recovery] -``` - -### Replica Set Features - -- Cluster of N nodes. -- Any one node can be primary. -- All write operations go to the primary. -- Automatic failover and recovery. -- Consensus election of primary. - -## Set Up a Replica Set - -To set up a replica set, follow these steps: - -1. Shutdown the running MongoDB server. -2. Start the MongoDB server with the `--replSet` option: - - ```shell - mongod --port "PORT" --dbpath "YOUR_DB_DATA_PATH" --replSet "REPLICA_SET_INSTANCE_NAME" - ``` - - Example: - ```shell - mongod --port 27017 --dbpath "D:\set up\mongodb\data" --replSet rs0 - ``` - -3. Connect to this mongod instance and issue the command `rs.initiate()` to initiate a new replica set. -4. Use `rs.conf()` to check the replica set configuration and `rs.status()` to check the status of the replica set. - -## Add Members to Replica Set - -To add members to a replica set: - -1. Start mongod instances on multiple machines. -2. Connect to the primary node in the Mongo client. -3. Issue the `rs.add()` command to add members to the replica set. - -### Syntax - -```shell ->rs.add(HOST_NAME:PORT) -``` - -Example: - -```shell ->rs.add("mongod1.net:27017") -``` - -> **NOTE :** You can add mongod instances to the replica set only when connected to the primary node. Use `db.isMaster()` to check your connection status. diff --git a/docs/MongoDB/mongodb-sharding.md b/docs/MongoDB/mongodb-sharding.md deleted file mode 100644 index 523a00b0d..000000000 --- a/docs/MongoDB/mongodb-sharding.md +++ /dev/null @@ -1,67 +0,0 @@ ---- -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 diff --git a/docs/MongoDB/mongodb-sort-records.md b/docs/MongoDB/mongodb-sort-records.md deleted file mode 100644 index 033451804..000000000 --- a/docs/MongoDB/mongodb-sort-records.md +++ /dev/null @@ -1,75 +0,0 @@ ---- -id: mongodb-sort-records -title: MongoDB - Sort Records -sidebar_label: Sort Records -sidebar_position: 17 -tags: [mongodb, sort, records, commands] -description: Learn how to sort records in MongoDB collections using the sort() method. ---- - -# MongoDB - Sort Records - -In this chapter, we will learn how to sort records in MongoDB. - -## The sort() Method - -To sort documents in MongoDB, you need to use the `sort()` method. The method accepts a document containing a list of fields along with their sorting order. To specify sorting order, `1` and `-1` are used. `1` is used for ascending order while `-1` is used for descending order. - -### Syntax - -The basic syntax of the `sort()` method is as follows: - -```bash -> db.COLLECTION_NAME.find().sort({KEY:1}) -``` - -### Example - -Consider the collection `mycol` has the following data: - -```json -{ "_id" : ObjectId("507f191e810c19729de860e1"), "title": "MongoDB Overview" } -{ "_id" : ObjectId("507f191e810c19729de860e2"), "title": "NoSQL Overview" } -{ "_id" : ObjectId("507f191e810c19729de860e3"), "title": "Tutorials Point Overview" } -``` - -The following example will display the documents sorted by title in descending order: - -```bash -> db.mycol.find({},{"title":1,_id:0}).sort({"title":-1}) -{"title":"Tutorials Point Overview"} -{"title":"NoSQL Overview"} -{"title":"MongoDB Overview"} -``` - -Please note, if you don't specify the sorting preference, the `sort()` method will display the documents in ascending order. - -## Diagram - -### Sorting Operation Flow -```mermaid -graph TD; - A[Start] --> B[Specify Collection] - B --> C{Set Sort Order} - C -->|Ascending| D["Apply sort ({KEY:1})"] - C -->|Descending| E["Apply sort ({KEY:-1})"] - D --> F["Execute find() with Sort"] - E --> F["Execute find() with Sort"] - F --> G[Display Sorted Results] - G --> H[End] -``` - -## Notes - -- The `sort()` method is used to order the documents returned in the query result. -- Sorting can be specified in ascending order (`1`) or descending order (`-1`). -- If no sorting preference is specified, documents are sorted in ascending order by default. - -## Table of Commands - -| Command | Description | -| ------- | ----------- | -| `db.COLLECTION_NAME.find().sort({KEY:1})` | Sorts the documents in ascending order by the specified key. | -| `db.COLLECTION_NAME.find().sort({KEY:-1})` | Sorts the documents in descending order by the specified key. | -| `db.COLLECTION_NAME.find({}, {"title": 1, "_id": 0}).sort({"title": -1})` | Retrieves documents sorted by the `title` field in descending order, displaying only the `title` field. | -| `db.COLLECTION_NAME.find({}, {"title": 1, "_id": 0}).sort({"title": 1})` | Retrieves documents sorted by the `title` field in ascending order, displaying only the `title` field. | diff --git a/docs/MongoDB/overview.md b/docs/MongoDB/overview.md deleted file mode 100644 index 248a0ec52..000000000 --- a/docs/MongoDB/overview.md +++ /dev/null @@ -1,63 +0,0 @@ ---- -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. diff --git a/docs/MongoDB/query-document.md b/docs/MongoDB/query-document.md deleted file mode 100644 index 37f8d0322..000000000 --- a/docs/MongoDB/query-document.md +++ /dev/null @@ -1,294 +0,0 @@ ---- -id: mongodb-query-document -title: MongoDB - Query Document -sidebar_label: Query Document -sidebar_position: 12 -tags: [mongodb, query, document, commands] -description: Learn how to query documents from MongoDB collections using various methods. ---- - -# MongoDB - Query Document - -In this chapter, we will learn how to query documents from a MongoDB collection. - -## The `find()` Method - -To query data from a MongoDB collection, you need to use MongoDB's `find()` method. - -### Syntax -The basic syntax of the `find()` method is as follows: -```javascript -db.COLLECTION_NAME.find() -``` -The `find()` method will display all the documents in a non-structured way. - -### Example -Assume we have created a collection named `mycol` as follows: -```javascript -> use sampleDB -switched to db sampleDB -> db.createCollection("mycol") -{ "ok" : 1 } -> -``` -And inserted 3 documents in it using the `insert()` method as shown below: -```javascript -> db.mycol.insert([ - { - title: "MongoDB Overview", - description: "MongoDB is no SQL database", - by: "tutorials point", - url: "http://www.tutorialspoint.com", - tags: ["mongodb", "database", "NoSQL"], - likes: 100 - }, - { - title: "NoSQL Database", - description: "NoSQL database doesn't have tables", - by: "tutorials point", - url: "http://www.tutorialspoint.com", - tags: ["mongodb", "database", "NoSQL"], - likes: 20, - comments: [ - { - user:"user1", - message: "My first comment", - dateCreated: new Date(2013,11,10,2,35), - like: 0 - } - ] - } -]) -``` - -Following method retrieves all the documents in the collection: -```javascript -> db.mycol.find() -{ "_id" : ObjectId("5dd4e2cc0821d3b44607534c"), "title" : "MongoDB Overview", "description" : "MongoDB is no SQL database", "by" : "tutorials point", "url" : "http://www.tutorialspoint.com", "tags" : [ "mongodb", "database", "NoSQL" ], "likes" : 100 } -{ "_id" : ObjectId("5dd4e2cc0821d3b44607534d"), "title" : "NoSQL Database", "description" : "NoSQL database doesn't have tables", "by" : "tutorials point", "url" : "http://www.tutorialspoint.com", "tags" : [ "mongodb", "database", "NoSQL" ], "likes" : 20, "comments" : [ { "user" : "user1", "message" : "My first comment", "dateCreated" : ISODate("2013-12-09T21:05:00Z"), "like" : 0 } ] } -``` - -## The `pretty()` Method -To display the results in a formatted way, you can use the `pretty()` method. - -### Syntax -```javascript -db.COLLECTION_NAME.find().pretty() -``` - -### Example -Following example retrieves all the documents from the collection named `mycol` and arranges them in an easy-to-read format. -```javascript -> db.mycol.find().pretty() -{ - "_id" : ObjectId("5dd4e2cc0821d3b44607534c"), - "title" : "MongoDB Overview", - "description" : "MongoDB is no SQL database", - "by" : "tutorials point", - "url" : "http://www.tutorialspoint.com", - "tags" : [ - "mongodb", - "database", - "NoSQL" - ], - "likes" : 100 -} -{ - "_id" : ObjectId("5dd4e2cc0821d3b44607534d"), - "title" : "NoSQL Database", - "description" : "NoSQL database doesn't have tables", - "by" : "tutorials point", - "url" : "http://www.tutorialspoint.com", - "tags" : [ - "mongodb", - "database", - "NoSQL" - ], - "likes" : 20, - "comments" : [ - { - "user" : "user1", - "message" : "My first comment", - "dateCreated" : ISODate("2013-12-09T21:05:00Z"), - "like" : 0 - } - ] -} -``` - -## The `findOne()` Method -Apart from the `find()` method, there is a `findOne()` method, that returns only one document. - -### Syntax -```javascript -db.COLLECTIONNAME.findOne() -``` - -### Example -Following example retrieves the document with title "MongoDB Overview". -```javascript -> db.mycol.findOne({title: "MongoDB Overview"}) -{ - "_id" : ObjectId("5dd6542170fb13eec3963bf0"), - "title" : "MongoDB Overview", - "description" : "MongoDB is no SQL database", - "by" : "tutorials point", - "url" : "http://www.tutorialspoint.com", - "tags" : [ - "mongodb", - "database", - "NoSQL" - ], - "likes" : 100 -} -``` - -## RDBMS Where Clause Equivalents in MongoDB -To query the document on the basis of some condition, you can use the following operations. - -### Table: MongoDB Query Operators and RDBMS Equivalents -| Operation | Syntax | Example | RDBMS Equivalent | -|-------------------------|------------------------------|-----------------------------------------------------------|------------------------------| -| **Equality** | `{:{$eq:}}` | `db.mycol.find({"by":"tutorials point"}).pretty()` | `where by = 'tutorials point'` | -| **Less Than** | `{:{$lt:}}` | `db.mycol.find({"likes":{$lt:50}}).pretty()` | `where likes < 50` | -| **Less Than Equals** | `{:{$lte:}}` | `db.mycol.find({"likes":{$lte:50}}).pretty()` | `where likes <= 50` | -| **Greater Than** | `{:{$gt:}}` | `db.mycol.find({"likes":{$gt:50}}).pretty()` | `where likes > 50` | -| **Greater Than Equals** | `{:{$gte:}}` | `db.mycol.find({"likes":{$gte:50}}).pretty()` | `where likes >= 50` | -| **Not Equals** | `{:{$ne:}}` | `db.mycol.find({"likes":{$ne:50}}).pretty()` | `where likes != 50` | -| **Values in an array** | `{:{$in:[]}}` | `db.mycol.find({"name":{$in:["Raj", "Ram", "Raghu"]}}).pretty()` | `Where name in ["Raj", "Ram", "Raghu"]` | -| **Values not in an array** | `{:{$nin:}}` | `db.mycol.find({"name":{$nin:["Ramu", "Raghav"]}}).pretty()` | `Where name not in ["Ramu", "Raghav"]` | - -## AND in MongoDB - -### Syntax -To query documents based on the AND condition, you need to use the `$and` keyword. Following is the basic syntax of AND: -```javascript -db.mycol.find({ $and: [ {:}, { :} ] }) -``` - -### Example -The following example will show all the tutorials written by 'tutorials point' and whose title is 'MongoDB Overview': -```javascript -> db.mycol.find({$and:[{"by":"tutorials point"},{"title": "MongoDB Overview"}]}).pretty() -{ - "_id" : ObjectId("5dd4e2cc0821d3b44607534c"), - "title" : "MongoDB Overview", - "description" : "MongoDB is no SQL database", - "by" : "tutorials point", - "url" : "http://www.tutorialspoint.com", - "tags" : [ - "mongodb", - "database", - "NoSQL" - ], - "likes" : 100 -} -``` - -## OR in MongoDB - -### Syntax -To query documents based on the OR condition, you need to use the `$or` keyword. Following is the basic syntax of OR: -```javascript -db.mycol.find( - { - $or: [ - {key1: value1}, {key2:value2} - ] - } -).pretty() -``` - -### Example -The following example will show all the tutorials written by 'tutorials point' or whose title is 'MongoDB Overview': -```javascript -> db.mycol.find({$or:[{"by":"tutorials point"},{"title": "MongoDB Overview"}]}).pretty() -{ - "_id": ObjectId(7df78ad8902c), - "title": "MongoDB Overview", - "description": "MongoDB is no sql database", - "by": "tutorials point", - "url": "http://www.tutorialsp - -oint.com", - "tags": ["mongodb", "database", "NoSQL"], - "likes": 100 -} -{ - "_id": ObjectId(7df78ad8902c), - "title": "MongoDB Overview", - "description": "MongoDB is no sql database", - "by": "XYZ", - "url": "http://www.tutorialspoint.com", - "tags": ["mongodb", "database", "NoSQL"], - "likes": 20 -} -``` - -## Limiting Records -To limit the records in MongoDB, you need to use the `limit()` method. - -### Syntax -```javascript -db.COLLECTION_NAME.find().limit(NUMBER) -``` - -### Example -The following example will retrieve only 2 documents: -```javascript -> db.mycol.find().limit(2) -{ "_id" : ObjectId("5dd4e2cc0821d3b44607534c"), "title" : "MongoDB Overview", "description" : "MongoDB is no SQL database", "by" : "tutorials point", "url" : "http://www.tutorialspoint.com", "tags" : [ "mongodb", "database", "NoSQL" ], "likes" : 100 } -{ "_id" : ObjectId("5dd4e2cc0821d3b44607534d"), "title" : "NoSQL Database", "description" : "NoSQL database doesn't have tables", "by" : "tutorials point", "url" : "http://www.tutorialspoint.com", "tags" : [ "mongodb", "database", "NoSQL" ], "likes" : 20, "comments" : [ { "user" : "user1", "message" : "My first comment", "dateCreated" : ISODate("2013-12-09T21:05:00Z"), "like" : 0 } ] } -``` - -## Sorting the Results -To sort the documents in MongoDB, you need to use the `sort()` method. - -### Syntax -```javascript -db.COLLECTION_NAME.find().sort({KEY:1}) -``` -- 1 is for ascending order -- -1 is for descending order - -### Example -Following example will sort the documents by title in ascending order: -```javascript -> db.mycol.find().sort({title:1}).pretty() -{ - "_id" : ObjectId("5dd4e2cc0821d3b44607534d"), - "title" : "NoSQL Database", - "description" : "NoSQL database doesn't have tables", - "by" : "tutorials point", - "url" : "http://www.tutorialspoint.com", - "tags" : [ - "mongodb", - "database", - "NoSQL" - ], - "likes" : 20, - "comments" : [ - { - "user" : "user1", - "message" : "My first comment", - "dateCreated" : ISODate("2013-12-09T21:05:00Z"), - "like" : 0 - } - ] -} -{ - "_id" : ObjectId("5dd4e2cc0821d3b44607534c"), - "title" : "MongoDB Overview", - "description" : "MongoDB is no SQL database", - "by" : "tutorials point", - "url" : "http://www.tutorialspoint.com", - "tags" : [ - "mongodb", - "database", - "NoSQL" - ], - "likes" : 100 -} -``` - -This chapter covers the basic querying methods in MongoDB, including how to use the `find()`, `pretty()`, `findOne()`, `limit()`, and `sort()` methods, and how to implement conditional queries with the `$and` and `$or` operators. \ No newline at end of file diff --git a/docs/MongoDB/update-document.md b/docs/MongoDB/update-document.md deleted file mode 100644 index 3070fa679..000000000 --- a/docs/MongoDB/update-document.md +++ /dev/null @@ -1,250 +0,0 @@ ---- -id: mongodb-update-document -title: MongoDB - Update Document -sidebar_label: Update Document -sidebar_position: 13 -tags: [mongodb, update, document, commands] -description: Learn how to update documents in MongoDB collections using different methods. ---- - -# MongoDB - Update Document - -MongoDB's `update()` and `save()` methods are used to update documents in a collection. The `update()` method updates the values in the existing document, while the `save()` method replaces the existing document with the document passed in the `save()` method. - -## MongoDB `update()` Method - -The `update()` method updates the values in the existing document. - -### Syntax - -The basic syntax of the `update()` method is as follows: - -```shell -db.COLLECTION_NAME.update(SELECTION_CRITERIA, UPDATED_DATA) -``` - -### Example - -Consider the `mycol` collection has the following data: - -```json -{ "_id" : ObjectId(5983548781331adf45ec5), "title":"MongoDB Overview"} -{ "_id" : ObjectId(5983548781331adf45ec6), "title":"NoSQL Overview"} -{ "_id" : ObjectId(5983548781331adf45ec7), "title":"Tutorials Point Overview"} -``` - -The following example sets the new title 'New MongoDB Tutorial' for the documents whose title is 'MongoDB Overview'. - -```shell -db.mycol.update({'title':'MongoDB Overview'}, {$set:{'title':'New MongoDB Tutorial'}}) -``` - -```shell -WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 }) -``` - -```shell -db.mycol.find() -{ "_id" : ObjectId(5983548781331adf45ec5), "title":"New MongoDB Tutorial"} -{ "_id" : ObjectId(5983548781331adf45ec6), "title":"NoSQL Overview"} -{ "_id" : ObjectId(5983548781331adf45ec7), "title":"Tutorials Point Overview"} -``` - -### Note -By default, MongoDB will update only a single document. To update multiple documents, you need to set the `multi` parameter to true. - -```shell -db.mycol.update({'title':'MongoDB Overview'}, {$set:{'title':'New MongoDB Tutorial'}}, {multi:true}) -``` - -## MongoDB `save()` Method - -The `save()` method replaces the existing document with the new document passed in the `save()` method. - -### Syntax - -The basic syntax of the MongoDB `save()` method is shown below: - -```shell -db.COLLECTION_NAME.save({_id:ObjectId(), NEW_DATA}) -``` - -### Example - -The following example replaces the document with the `_id` '5983548781331adf45ec5'. - -```shell -db.mycol.save({ - "_id" : ObjectId("507f191e810c19729de860ea"), - "title":"Tutorials Point New Topic", - "by":"Tutorials Point" -}) -``` - -```shell -WriteResult({ - "nMatched" : 0, - "nUpserted" : 1, - "nModified" : 0, - "_id" : ObjectId("507f191e810c19729de860ea") -}) -``` - -```shell -db.mycol.find() -{ "_id" : ObjectId("507f191e810c19729de860ea"), "title":"Tutorials Point New Topic", "by":"Tutorials Point"} -{ "_id" : ObjectId("507f191e810c19729de860e6"), "title":"NoSQL Overview"} -{ "_id" : ObjectId("507f191e810c19729de860e7"), "title":"Tutorials Point Overview"} -``` - -## MongoDB `findOneAndUpdate()` Method - -The `findOneAndUpdate()` method updates the values in the existing document. - -### Syntax - -The basic syntax of the `findOneAndUpdate()` method is as follows: - -```shell -db.COLLECTION_NAME.findOneAndUpdate(SELECTION_CRITERIA, UPDATED_DATA) -``` - -### Example - -Assume we have created a collection named `empDetails` and inserted three documents in it as shown below: - -```json -db.empDetails.insertMany([ - { - "First_Name": "Radhika", - "Last_Name": "Sharma", - "Age": "26", - "e_mail": "radhika_sharma.123@gmail.com", - "phone": "9000012345" - }, - { - "First_Name": "Rachel", - "Last_Name": "Christopher", - "Age": "27", - "e_mail": "Rachel_Christopher.123@gmail.com", - "phone": "9000054321" - }, - { - "First_Name": "Fathima", - "Last_Name": "Sheik", - "Age": "24", - "e_mail": "Fathima_Sheik.123@gmail.com", - "phone": "9000054321" - } -]) -``` - -The following example updates the age and email values of the document with the name 'Radhika'. - -```shell -db.empDetails.findOneAndUpdate( - {First_Name: 'Radhika'}, - { $set: { Age: '30', e_mail: 'radhika_newemail@gmail.com'}} -) -``` - -```json -{ - "_id" : ObjectId("5dd6636870fb13eec3963bf5"), - "First_Name" : "Radhika", - "Last_Name" : "Sharma", - "Age" : "30", - "e_mail" : "radhika_newemail@gmail.com", - "phone" : "9000012345" -} -``` - -## MongoDB `updateOne()` Method - -This method updates a single document that matches the given filter. - -### Syntax - -The basic syntax of the `updateOne()` method is as follows: - -```shell -db.COLLECTION_NAME.updateOne(, ) -``` - -### Example - -```shell -db.empDetails.updateOne( - {First_Name: 'Radhika'}, - { $set: { Age: '30', e_mail: 'radhika_newemail@gmail.com'}} -) -``` - -```shell -{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 0 } -``` - -## MongoDB `updateMany()` Method - -The `updateMany()` method updates all the documents that match the given filter. - -### Syntax - -The basic syntax of the `updateMany()` method is as follows: - -```shell -db.COLLECTION_NAME.updateMany(, ) -``` - -### Example - -```shell -db.empDetails.updateMany( - {Age: { $gt: "25" }}, - { $set: { Age: '00'}} -) -``` - -```shell -{ "acknowledged" : true, "matchedCount" : 2, "modifiedCount" : 2 } -``` - -### Viewing Updated Documents - -You can see the updated values if you retrieve the contents of the document using the `find` method as shown below: - -```shell -db.empDetails.find() -{ "_id" : ObjectId("5dd6636870fb13eec3963bf5"), "First_Name" : "Radhika", "Last_Name" : "Sharma", "Age" : "00", "e_mail" : "radhika_newemail@gmail.com", "phone" : "9000012345" } -{ "_id" : ObjectId("5dd6636870fb13eec3963bf6"), "First_Name" : "Rachel", "Last_Name" : "Christopher", "Age" : "00", "e_mail" : "Rachel_Christopher.123@gmail.com", "phone" : "9000054321" } -{ "_id" : ObjectId("5dd6636870fb13eec3963bf7"), "First_Name" : "Fathima", "Last_Name" : "Sheik", "Age" : "24", "e_mail" : "Fathima_Sheik.123@gmail.com", "phone" : "9000054321" } -``` - -## Diagram - -```mermaid -graph TD; - A[MongoDB Update Methods] --> B[update method] - A --> C[save method] - A --> D[findOneAndUpdate method] - A --> E[updateOne method] - A --> F[updateMany method] -``` - -## Note - -- The `update()` method updates the values in the existing document based on the selection criteria. -- The `save()` method replaces the entire document. -- The `findOneAndUpdate()` method finds a single document and updates it. -- The `updateOne()` method updates one document that matches the filter. -- The `updateMany()` method updates all documents that match the filter. - -## Table of MongoDB Update Methods - -| Method | Description | -|----------------------|---------------------------------------------| -| `update()` | Updates values in the existing document | -| `save()` | Replaces the existing document | -| `findOneAndUpdate()` | Finds and updates a single document | -| `updateOne()` | Updates one document that matches the filter| -| `updateMany()` | Updates all documents that match the filter | diff --git a/docs/Vue.js/_category_.json b/docs/Vue.js/_category_.json deleted file mode 100644 index 8c1a0c909..000000000 --- a/docs/Vue.js/_category_.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "label": "Vue.Js", - "position": 27, - "link": { - "type": "generated-index", - "description": "Vue.js is a progressive JavaScript framework used for building user interfaces." - } - } \ No newline at end of file diff --git a/docs/Vue.js/intro.md b/docs/Vue.js/intro.md deleted file mode 100644 index a5a746150..000000000 --- a/docs/Vue.js/intro.md +++ /dev/null @@ -1,104 +0,0 @@ ---- -id: vue-js-introduction -title: Vue.js Introduction -sidebar_label: Introduction -sidebar_position: 1 -tags: [Vue.js,JavaScript,Vue.js Introduction,Framework] -description: What is Vue.Js and Fundamentals. ---- - -Vue.js is a progressive JavaScript framework for building user interfaces. It is designed from the ground up to be incrementally adoptable, meaning that you can integrate Vue.js into an existing project or use it to build a new application from scratch. Vue.js is known for its simplicity, flexibility, and performance, making it a popular choice for developers of all skill levels. - - - -## Introduction: - -Vue.js is a modern JavaScript framework that focuses on the view layer of web applications. It provides a simple and intuitive API for building interactive user interfaces and single-page applications. Vue.js is inspired by Angular and React but aims to be more lightweight and flexible. - -## Key Features: - -Here are some key features of Vue.js that make it stand out: - -1. **Reactive Data Binding:** Vue.js uses a reactive data model that allows you to declaratively bind data to the DOM. When the data changes, the DOM updates automatically, making it easy to build dynamic and responsive applications. -2. **Component-Based Architecture:** Vue.js encourages the use of reusable components to build complex user interfaces. Components are self-contained units of functionality that can be composed together to create a complete application. -3. **Virtual DOM:** Vue.js uses a virtual DOM to optimize rendering performance. When data changes, Vue.js updates the virtual DOM and efficiently applies the changes to the real DOM, minimizing the number of DOM manipulations. -4. **Directives:** Vue.js provides a set of built-in directives that allow you to add dynamic behavior to your templates. Directives are prefixed with `v-` and can be used to conditionally render elements, bind data, and listen to events. -5. **Computed Properties:** Vue.js allows you to define computed properties that are derived from other data properties. Computed properties are cached based on their dependencies and are updated automatically when the dependencies change. -6. **Watchers:** Vue.js provides watchers that allow you to react to changes in data properties. Watchers are useful for performing asynchronous operations, side effects, or custom logic in response to data changes. -7. **Lifecycle Hooks:** Vue.js provides a set of lifecycle hooks that allow you to run code at specific stages of a component's lifecycle. You can use lifecycle hooks to perform initialization, cleanup, or other tasks when a component is created, mounted, updated, or destroyed. -8. **Routing:** Vue.js provides an official router library called Vue Router that allows you to implement client-side routing in your applications. Vue Router supports nested routes, route parameters, navigation guards, and other advanced features. -9. **State Management:** Vue.js provides an official state management library called Vuex that allows you to manage application state in a centralized store. Vuex supports features like modules, actions, mutations, and getters for managing complex state logic. -10. **Devtools:** Vue.js provides a browser extension called Vue Devtools that allows you to inspect and debug Vue.js applications. Vue Devtools provides a visual component tree, state inspector, event log, and time-travel debugging capabilities. -11. **Server-Side Rendering:** Vue.js supports server-side rendering (SSR) out of the box, allowing you to render Vue components on the server and send the generated HTML to the client. SSR improves performance, SEO, and initial load times for your applications. -12. **TypeScript Support:** Vue.js has first-class support for TypeScript, a statically typed superset of JavaScript. You can write Vue components in TypeScript and benefit from type checking, autocompletion, and other TypeScript features. -13. **Community Ecosystem:** Vue.js has a vibrant community that maintains a rich ecosystem of plugins, components, tools, and resources. You can find official and third-party libraries for integrating Vue.js with other technologies, frameworks, and services. -14. **Learning Resources:** Vue.js provides comprehensive documentation, tutorials, guides, and examples to help you learn and master the framework. You can find official and community-contributed resources for getting started with Vue.js, building projects, and solving common problems. - - - -## Getting Started: - -To get started with Vue.js, you can follow these steps: - -1. **Installation:** You can install Vue.js via a CDN, npm, or yarn. For example, you can include Vue.js via a CDN in your HTML file: - - ```html - - ``` - - Or install Vue.js using npm: - - ```bash - npm install vue@2.6.14 - ``` - -2. **Hello World Example:** You can create a simple "Hello World" example using Vue.js by adding the following code to your HTML file: - - ```html -
- {{ message }} -
- - - ``` -3. **Component Example:** You can create a reusable component using Vue.js by defining a new Vue component: - - ```html -
- -
- - - ``` -4. **Vue CLI:** You can use the Vue CLI to scaffold a new Vue.js project, manage dependencies, and build your application. You can install the Vue CLI globally using npm: - - ```bash - npm install -g @vue/cli - ``` - - And create a new Vue project using the Vue CLI: - - ```bash - vue create my-project - ``` - - You can choose from various project templates, features, and configurations when creating a new Vue project with the Vue CLI. - -## Conclusion: - -Vue.js is a powerful and versatile framework for building modern web applications. It provides a rich set of features, tools, and resources that make it easy to develop interactive and responsive user interfaces. Whether you are a beginner or an experienced developer, Vue.js offers a flexible and intuitive API that can help you build high-quality applications with ease. If you are looking for a modern JavaScript framework that is simple, lightweight, and performant, Vue.js is a great choice to consider. \ No newline at end of file diff --git a/docs/blog.mdx b/docs/blog.mdx new file mode 100644 index 000000000..8857c040c --- /dev/null +++ b/docs/blog.mdx @@ -0,0 +1,191 @@ +--- +description: Learn how to build and manage a complete blog using Docusaurus. +--- + +# Blog + +The **Blog** feature in Docusaurus lets you create a full-featured, customizable blog with minimal setup. +It supports Markdown/MDX posts, authors, tags, feeds, and multiple configuration options—perfect for sharing updates, tutorials, or news. + +:::info +See the [Blog Plugin API Reference](https://docusaurus.io/docs/api/plugins/@docusaurus/plugin-content-blog) for the full list of options and advanced configuration. +::: + + + +## Getting Started {#getting-started} + +1. **Create a `blog` directory** in the root of your project. +2. Add a navbar item to point to the blog in `docusaurus.config.js`: + +```js title="docusaurus.config.js" +export default { + themeConfig: { + navbar: { + items: [ + // highlight-next-line + { to: 'blog', label: 'Blog', position: 'left' }, + ], + }, + }, +}; +```` + +Once added, Docusaurus will automatically generate routes for your blog posts. + +## Writing Posts {#writing-posts} + +Each post is a Markdown (`.md`) or MDX (`.mdx`) file inside the `blog` folder. +Use [front matter](/docs/markdown-features#front-matter) to define metadata such as title, description, author, and tags. + +Example: + +```md title="blog/2025-09-01-hello-blog.md" +--- +title: Hello Blog +description: My first Docusaurus blog post! +authors: + - name: Ajay Dhangar + url: https://github.com/ajay-dhangar + image_url: https://github.com/ajay-dhangar.png +tags: [introduction, welcome] +image: /img/blog-banner.png +hide_table_of_contents: false +--- + +Welcome to my new CodeHarborHub blog! +This is where I’ll share updates, tips, and tutorials. + + + +Everything below the truncate marker will only appear on the full post page. +``` + +* The `` marker defines the preview shown on the blog list page. +* MDX files can use `{/* truncate */}` instead. + +## Customizing the Blog {#customizing} + +You can tweak blog behavior in the `@docusaurus/preset-classic` configuration: + +```js title="docusaurus.config.js" +export default { + presets: [ + [ + '@docusaurus/preset-classic', + { + blog: { + blogTitle: 'CodeHarborHub Blog', + blogDescription: 'Updates, tutorials, and tech insights.', + postsPerPage: 'ALL', // Disable pagination + blogSidebarTitle: 'All Posts', + blogSidebarCount: 'ALL', // Show all posts in sidebar + showReadingTime: true, // Display estimated reading time + }, + }, + ], + ], +}; +``` + + + +### Reading Time + +You can provide a custom reading time algorithm: + +```js title="docusaurus.config.js" +export default { + presets: [ + [ + '@docusaurus/preset-classic', + { + blog: { + readingTime: ({ content, defaultReadingTime }) => + defaultReadingTime({ content, options: { wordsPerMinute: 250 } }), + }, + }, + ], + ], +}; +``` + +### Feeds + +Generate **RSS/Atom/JSON** feeds for subscribers: + +```js title="docusaurus.config.js" +export default { + presets: [ + [ + '@docusaurus/preset-classic', + { + blog: { + feedOptions: { + type: 'all', + copyright: `© ${new Date().getFullYear()} CodeHarborHub`, + }, + }, + }, + ], + ], +}; +``` + +Feeds are available at: + + +`/blog/rss.xml` +`/blog/atom.xml` +`/blog/feed.json` + + + + +## Blog-only Mode {#blog-only-mode} + +Want your blog to be the homepage? +Disable docs and serve the blog at the root: + +```js title="docusaurus.config.js" +export default { + presets: [ + [ + '@docusaurus/preset-classic', + { + docs: false, + blog: { + routeBasePath: '/', // Serve blog at site root + }, + }, + ], + ], +}; +``` + +Remove `src/pages/index.js` if it exists to avoid route conflicts. + +## Multiple Blogs {#multiple-blogs} + +You can run more than one blog by adding additional plugin instances: + +```js title="docusaurus.config.js" +export default { + plugins: [ + [ + '@docusaurus/plugin-content-blog', + { + id: 'news', + routeBasePath: 'news', + path: './news', + }, + ], + ], +}; +``` + +This creates a second blog at `/news` with its own posts. + +--- + +With these options, you can quickly deploy a modern, SEO-friendly blog, customize layouts, manage multiple authors, and grow your content with ease. \ No newline at end of file diff --git a/docs/browser-support.mdx b/docs/browser-support.mdx new file mode 100644 index 000000000..9df0c0829 --- /dev/null +++ b/docs/browser-support.mdx @@ -0,0 +1,133 @@ +--- +id: browser-support +description: Learn how CodeHarborHub manages browser compatibility while keeping bundle size small +sidebar_label: Browser Support +keywords: + - browserslist + - compatibility + - codeharborhub + - bundle size +--- + +# Browser Support + +CodeHarborHub uses the **[Browserslist](https://github.com/browserslist/browserslist)** configuration to define which browsers are supported during builds. +This ensures a balance between **backward compatibility** and **optimized bundle size**. + + + +## Purpose {#purpose} + +Older browsers often lack support for modern JavaScript syntax and APIs. +Supporting them requires extra code (polyfills, transpilation), which **increases the final JS bundle size** and slows down loading times. + +For example, CodeHarborHub uses the [optional chaining syntax](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining): + +```js +const value = user?.profile?.email; +``` + +Older browsers may not understand this syntax, so the production build will **transpile** it into a more verbose but compatible form: + +```js +var _user, _user$profile; + +const value = + (_user = user) === null || _user === void 0 + ? void 0 + : (_user$profile = _user.profile) === null || _user$profile === void 0 + ? void 0 + : _user$profile.email; +``` + +This keeps the code running everywhere—but also makes the bundle larger. + + + +## Default Configuration {#default-configuration} + +The default CodeHarborHub template includes the following **browserslist** field in `package.json`: + +```json title="package.json" +{ + "name": "codeharborhub", + // ... + "browserslist": { + "production": [">0.5%", "not dead", "not op_mini all"], + "development": [ + "last 1 chrome version", + "last 1 firefox version", + "last 1 safari version" + ] + } +} +``` + +### Meaning: + +* **Production**: Support browsers with + + * > 0.5% global market share + * Still officially maintained (`not dead`) + * Excluding Opera Mini (extremely limited) +* **Development**: Only the latest versions of Chrome, Firefox, and Safari for faster local builds. + + + +## Checking the Actual List {#checking-list} + +Run the Browserslist CLI to see which browsers match the configuration: + +```bash +npx browserslist --env="production" +``` + +Example output (for 2025): + +```text +chrome 124 +edge 124 +firefox 125 +ios_saf 17 +safari 17 +android 124 +``` + +This represents the real browsers that your production build targets. + + + +## Adjusting Browser Targets {#adjusting-targets} + +You can customize browser support depending on your project needs. + +Examples: + +```json +"browserslist": { + "production": [">1%", "last 2 versions"], + "development": ["last 1 chrome version"] +} +``` + +* `>1%` – Only browsers with more than 1% market share. +* `last 2 versions` – Support the last two major versions of each browser. + + + +## Best Practices {#best-practices} + +* Keep production targets **inclusive but reasonable** to avoid large polyfills. +* Regularly check usage statistics for your audience (e.g., via [Can I Use](https://caniuse.com/)). +* Test your site on the most critical browsers after changing the config. +* Avoid supporting obsolete browsers like IE11 unless absolutely necessary. + + + +## Learn More {#learn-more} + +* [Browserslist README](https://github.com/browserslist/browserslist/blob/main/README.md) +* [Query Examples](https://github.com/browserslist/browserslist#queries) +* [Best Practices](https://github.com/browserslist/browserslist#best-practices) + +By carefully tuning browser support, CodeHarborHub ensures **fast loading times** while maintaining compatibility for the majority of users. \ No newline at end of file diff --git a/docs/configuration.mdx b/docs/configuration.mdx new file mode 100644 index 000000000..911b9a36a --- /dev/null +++ b/docs/configuration.mdx @@ -0,0 +1,223 @@ +--- +title: Configuration +description: "Configuring CodeHarborHub through docusaurus.config.js and customizing site behavior." +--- + +import TOCInline from '@theme/TOCInline'; + +:::info +Check the [**`docusaurus.config.js` API reference**](https://docusaurus.io/docs/api/docusaurus-config) +for a complete list of all available options. +::: + +CodeHarborHub is powered by **[Docusaurus](https://docusaurus.io/)**. Its configuration is centralized in a single file: **`docusaurus.config.js`**. This file defines your site’s metadata, theme options, plugins, and deployment settings. + +Keeping a well-maintained config helps contributors focus on docs and code while still allowing full customization. + + + +## Syntax to declare `docusaurus.config.js` {#syntax} + +The configuration file runs in **Node.js** and can export either: + +- a **config object**, or +- a **function** that returns a config object (sync or async). + +:::info + +The `docusaurus.config.js` file supports: + +- [**ES Modules**](https://flaviocopes.com/es-modules/) +- [**CommonJS**](https://flaviocopes.com/commonjs/) +- [**TypeScript**](./typescript-support.mdx#typing-config) + +Constraints: + +- **Required:** use `export default /* your config*/` (or `module.exports`) to export your Docusaurus config +- **Optional:** use `import Lib from 'lib'` (or `require('lib')`) to import Node.js packages + +::: + +Examples: + +```js title="docusaurus.config.js" +export default { + title: 'CodeHarborHub', + url: 'https://codeharborhub.github.io', + baseUrl: '/', +}; +```` + +```js title="docusaurus.config.js" +module.exports = { + title: 'CodeHarborHub', + url: 'https://codeharborhub.github.io', + baseUrl: '/', +}; +``` + +```ts title="docusaurus.config.ts" +import type {Config} from '@docusaurus/types'; + +export default { + title: 'CodeHarborHub', + url: 'https://codeharborhub.github.io', + baseUrl: '/', +} satisfies Config; +``` + +Async configs allow you to dynamically import ESM-only modules: + +```js title="docusaurus.config.js" +export default async function createConfig() { + const somePlugin = await import('remark-plugin'); + return { + title: 'CodeHarborHub', + url: 'https://codeharborhub.github.io', + baseUrl: '/', + plugins: [somePlugin.default], + }; +} +``` + + + +## Key Configuration Sections {#key-sections} + + + +### Site metadata {#site-metadata} + +Define global site information: + +```js title="docusaurus.config.js" +export default { + title: 'CodeHarborHub', + tagline: 'Learn. Build. Grow.', + url: 'https://codeharborhub.github.io', + baseUrl: '/', + favicon: 'img/favicon.ico', +}; +``` + +* **title** – Shown in the browser tab and search engines. +* **tagline** – Used in meta tags and the homepage hero. +* **url** & **baseUrl** – Base domain and subpath for deployment. +* **favicon** – Path to your site’s icon. + +### Deployment configurations {#deployment} + +If you plan to deploy to GitHub Pages: + +```js +export default { + organizationName: 'CodeHarborHub', // GitHub org/user + projectName: 'codeharborhub.github.io', // Repository name + deploymentBranch: 'gh-pages', +}; +``` + +See [Deployment](https://docusaurus.io/docs/deployment) for full instructions. + +### Theme, plugins, and presets {#theme-plugin-preset} + +List all themes, plugins, and presets to extend functionality: + +```js +export default { + plugins: [ + '@docusaurus/plugin-content-blog', + '@docusaurus/plugin-content-pages', + ], + themes: ['@docusaurus/theme-classic'], + presets: [ + [ + '@docusaurus/preset-classic', + { + docs: {sidebarPath: './sidebars.js'}, + blog: {showReadingTime: true}, + theme: {customCss: './src/css/custom.css'}, + }, + ], + ], +}; +``` + +💡 Use shorthands for convenience: + +```js +plugins: ['content-blog', 'content-pages'], +themes: ['classic'], +``` + +You can also load local plugins: + +```js +import path from 'path'; + +export default { + plugins: [path.resolve(__dirname, './plugins/customPlugin')], +}; +``` + +### Custom fields {#custom-fields} + +Add project-specific data under `customFields`: + +```js +export default { + customFields: { + repoUrl: 'https://github.com/CodeHarborHub/codeharborhub.github.io', + discordLink: 'https://discord.gg/', + }, +}; +``` + +These values can be accessed inside React components via `siteConfig`. + + + +## Accessing Configuration in Components {#accessing} + +Use the `useDocusaurusContext` hook to read config values: + +```jsx +import React from 'react'; +import useDocusaurusContext from '@docusaurus/useDocusaurusContext'; + +export default function FooterInfo() { + const {siteConfig} = useDocusaurusContext(); + return

© {new Date().getFullYear()} {siteConfig.title}

; +} +``` + +## Customizing Babel {#babel} + +Docusaurus transpiles source code with **Babel**. +To customize Babel, create a `babel.config.js` in your project root: + +```bash +npm install --save @docusaurus/babel +``` + +```js title="babel.config.js" +export default { + presets: ['@docusaurus/babel/preset'], +}; +``` + +Restart the dev server for changes to take effect. + + + +## Tips for CodeHarborHub {#tips} + +* Keep **SEO** fields (title, description, keywords) updated for better visibility. +* Use environment variables (`process.env`) for secrets like analytics keys. +* Store commonly reused links (GitHub, Discord) in `customFields` to update them in one place. + +--- + +🎯 With a well-structured `docusaurus.config.js`, +you can manage **site-wide settings, themes, and plugins** easily, +making CodeHarborHub scalable and contributor-friendly. \ No newline at end of file diff --git a/docs/css/_category_.json b/docs/css/_category_.json deleted file mode 100644 index 6da1ba5e6..000000000 --- a/docs/css/_category_.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "label": "CSS", - "position": 3, - "link": { - "type": "generated-index", - "description": "In this section, you will learn about the CSS." - } -} diff --git a/docs/css/backgrounds/_category_.json b/docs/css/backgrounds/_category_.json deleted file mode 100644 index cbc33a56b..000000000 --- a/docs/css/backgrounds/_category_.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "label": "Backgrounds", - "position": 4, - "link": { - "type": "generated-index", - "description": "In this section, you will learn about the CSS Backgrounds. CSS backgrounds are used to specify the background of an element. You can specify backgrounds using different methods such as background-color, background-image, background-repeat, background-attachment, background-position, and more." - } - } \ No newline at end of file diff --git a/docs/css/backgrounds/background-color.md b/docs/css/backgrounds/background-color.md deleted file mode 100644 index 09793e9f7..000000000 --- a/docs/css/backgrounds/background-color.md +++ /dev/null @@ -1,113 +0,0 @@ ---- -id: background-color -title: Background Color -sidebar_label: Background Color -sidebar_position: 1 -tags: [background, color, css background, background color] -description: Learn how to set the background color of an element in CSS using the background-color property. -keywords: - [ - background color, - css background color, - background-color property, - css background-color, - ] ---- - -In CSS, the `background-color` property is used to set the background color of an element. The `background-color` property accepts a color value, which can be specified using various color formats such as hexadecimal, RGB, RGBA, HSL, and HSLA. - - - -## Syntax - -The syntax for the `background-color` property is as follows: - -```css title="index.css" -selector { - background-color: color; -} -``` - -- `selector`: The element to which the background color is applied. -- `background-color`: The CSS property used to set the background color of an element. -- `color`: The color value used to specify the background color. -- The `color` value can be specified using various color formats, such as hexadecimal, RGB, RGBA, HSL, and HSLA. -- The `color` value can also be specified using color keywords like `red`, `blue`, `green`, etc. - -## Example - -In the following example, the `background-color` property is used to set the background color of a `
` element to a light blue color using the hexadecimal color format: - -```css title="index.css" -div { - background-color: #ADD8E6; /* Light blue color */ -} -``` - -In the HTML code below, the CSS rule will apply the light blue color to the background of the `
` element: - -```html title="index.html" -
This is a div with a light blue background.
-``` - -By using the `background-color` property, you can customize the background color of elements on your web page to create visually appealing designs. - - - -:::info Additional Information - -- The `background-color` property sets the background color of an element, covering the entire content area of the element. -- The `background-color` property can be combined with other background properties like `background-image`, `background-repeat`, `background-position`, etc., to create more complex background effects. -- When setting the background color of an element, ensure that there is enough contrast between the background color and the text color to ensure readability and accessibility. - -::: - -## Example for Background Color - -In this example, we will set the background color of a `
` element using the `background-color` property with an RGB color value: - - - - -```html showLineNumbers - - - - - - Background Color Example - - - -
This is a div with a light green background.
- - -``` - -
- - -```css showLineNumbers {2} -div { - background-color: rgb(144, 238, 144); /* Light green color */ -} -``` - - -
- -Now, you can see the output of the above code in the Browser Window like this: - - -<> -
This is a div with a light green background.
- -
- -In this example, the `background-color` property is used to set the background color of the `
` element to a light green color using the RGB color format. - -By specifying the background color using the `background-color` property, you can enhance the visual appearance of your web pages and create engaging user experiences. - -## Conclusion - -The `background-color` property in CSS allows you to set the background color of an element using various color formats. By customizing the background color of elements on your web page, you can create visually appealing designs and improve the overall user experience. \ No newline at end of file diff --git a/docs/css/backgrounds/background-image/_category_.json b/docs/css/backgrounds/background-image/_category_.json deleted file mode 100644 index 02a8df9f2..000000000 --- a/docs/css/backgrounds/background-image/_category_.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "label": "Background Image", - "position": 2, - "link": { - "type": "generated-index", - "description": "In this section, you will learn about the CSS Background Image. The background-image property sets one or more background images for an element. By default, a background-image is placed at the top-left corner of an element, and repeated both vertically and horizontally." - } - } \ No newline at end of file diff --git a/docs/css/backgrounds/background-image/background-attachment.md b/docs/css/backgrounds/background-image/background-attachment.md deleted file mode 100644 index 7378df4a4..000000000 --- a/docs/css/backgrounds/background-image/background-attachment.md +++ /dev/null @@ -1,134 +0,0 @@ ---- -id: background-attachment -title: Background Attachment -sidebar_label: Background Attachment -sidebar_position: 4 -tags: [background, css background, background attachment, background-attachment property] -description: Learn how to set the background attachment behavior of an element in CSS using the background-attachment property. -keywords: - [ - background attachment, - css background attachment, - background-attachment property, - css background-attachment, - ] ---- - -In CSS, the `background-attachment` property is used to specify whether the background image of an element scrolls with the content or remains fixed as the content moves. This property is used to control the attachment behavior of the background image. - - - -## Syntax - -The syntax for the `background-attachment` property is as follows: - -```css title="index.css" -selector { - background-attachment: value; -} -``` - -- `selector`: The element to which the background attachment behavior is applied. -- `background-attachment`: The CSS property used to set the background attachment behavior of an element. -- `value`: Specifies the attachment behavior of the background image. It can take one of the following values: - - `scroll`: The background image scrolls along with the content when the content is scrolled. - - `fixed`: The background image remains fixed within the viewport as the content is scrolled. - - `local`: The background image scrolls along with the element's contents, rather than the entire page. - - `initial`: Sets the background attachment behavior to its default value. -- The default value of the `background-attachment` property is `scroll`. - -## Example - -In the following example, the `background-attachment` property is used to set the background attachment behavior of a `
` element to `fixed`, which makes the background image remain fixed within the viewport as the content is scrolled: - -```css title="index.css" -div { - background-image: url('path/to/background-image.jpg'); - background-attachment: fixed; -} -``` - -In the HTML code below, the CSS rule will apply the `fixed` background attachment behavior to the background image of the `
` element: - -```html title="index.html" -
This is a div with a fixed background image.
-``` - -By using the `background-attachment` property, you can control how the background image behaves when the content is scrolled, allowing you to create various visual effects on your web page. - - - -:::info Additional Information - -- The `background-attachment` property is often used in combination with the `background-image` property to set a background image and define its attachment behavior. -- The `background-attachment` property can be used to create effects like parallax scrolling, where the background image moves at a different speed than the content, creating a sense of depth. - -::: - -## Example for background-attachment property - -In this example, we have a `
` element with a background image that has the `background-attachment` property set to `fixed`. This makes the background image remain fixed within the viewport as the content is scrolled: - - - - -```html showLineNumbers - - - - - - Background Attachment Example - - - -
-

Fixed Background Image

-

This is a div with a fixed background image.

-
- - -``` - -
- - -```css showLineNumbers {3} -div { - background-image: url('/assets/jpeg-image.jpg'); - background-attachment: fixed; - color: white; - text-align: center; - padding: 20px; -} - -h1 { - font-size: 2em; - margin-bottom: 0; -} - -p { - font-size: 1.2em; - margin-top: 0; -} -``` - - -
- -Now, you can see the output of the above code in the Browser Window like this: - - -<> -

Fixed Background Image

-

This is a div with a fixed background image.

- -
- -In this example, the background image remains fixed within the viewport as the content is scrolled, creating a visually appealing effect on the web page. - - - -## Conclusion - -The `background-attachment` property in CSS allows you to control the attachment behavior of the background image of an element. By setting the `background-attachment` property to `fixed`, `scroll`, `local`, or `initial`, you can create various visual effects on your web page. Experiment with different values of the `background-attachment` property to achieve the desired background image behavior for your elements. \ No newline at end of file diff --git a/docs/css/backgrounds/background-image/background-position.md b/docs/css/backgrounds/background-image/background-position.md deleted file mode 100644 index d3b1d030e..000000000 --- a/docs/css/backgrounds/background-image/background-position.md +++ /dev/null @@ -1,144 +0,0 @@ ---- -id: background-position -title: Background Position -sidebar_label: Background Position -sidebar_position: 3 -tags: [background, css background, background position, background-position property] -description: Learn how to set the position of the background image of an element in CSS using the background-position property. -keywords: - [ - background position, - css background position, - background-position property, - css background-position, - ] ---- - -In CSS, the `background-position` property is used to specify the position of the background image of an element. This property allows you to control the placement of the background image within the element's background area. - - - -## Syntax - -The syntax for the `background-position` property is as follows: - -```css title="index.css" -selector { - background-position: value; -} -``` - -- `selector`: The element to which the background position is applied. -- `background-position`: The CSS property used to set the position of the background image of an element. -- `value`: Specifies the position of the background image. It can take one of the following values: - - `top`: Aligns the top edge of the background image with the top edge of the background area. - - `bottom`: Aligns the bottom edge of the background image with the bottom edge of the background area. - - `left`: Aligns the left edge of the background image with the left edge of the background area. - - `right`: Aligns the right edge of the background image with the right edge of the background area. - - `center`: Aligns the background image in the center of the background area. - - ``: Specifies the position of the background image as a percentage of the background area. - - ``: Specifies the position of the background image using a length value (e.g., `10px`, `20%`). - - `initial`: Sets the background position to its default value. - - `inherit`: Inherits the background position from the parent element. - -The default value of the `background-position` property is `0% 0%`, which aligns the top left corner of the background image with the top left corner of the background area. - -## Example - -In the following example, the `background-position` property is used to set the position of the background image of a `
` element to `center`, which aligns the background image in the center of the background area: - -```css title="index.css" -div { - background-image: url("path/to/background-image.jpg"); - background-position: center; -} -``` - -In the HTML code below, the CSS rule will apply the `center` background position to the background image of the `
` element: - -```html title="index.html" -
-

- This is a div with a background image that is centered within the background area. -

-
-``` - -By using the `background-position` property, you can control the placement of the background image within the element's background area, allowing you to create visually appealing designs on your web page. - - - -:::note Try it yourself - -You can experiment with different values of the `background-position` property to position the background image in various ways within the background area of an element. Try changing the `background-position` value to `top`, `bottom`, `left`, `right`, or a specific length or percentage to see how the background image placement changes. - -::: - - -## Example for Background Position - -In this example, we will demonstrate how to use the `background-position` property to position the background image of a `
` element to the top right corner of the background area. - -### Step 1: Create an HTML File - -Create an HTML file named `index.html` and add the following code: - -```html title="index.html" showLineNumbers - - - - - - Background Position Example - - - -
-

- This is a div with a background image positioned at the top right corner. -

-
- - -``` - -### Step 2: Create a CSS File - -Create a CSS file named `styles.css` and add the following code to set the background image and position: - -```css title="styles.css" showLineNumbers {3} -div { - background-image: url("/assets/jpeg-image.jpg"); - background-position: top right; - height: 200px; - width: 400px; - border: 1px solid #333; - background-size: cover; color: #fff; -} - -p { - padding: 10px; -} -``` - -### Step 3: Add a Background Image - -Place an image file named `jpeg-image.jpg` in the `assets` directory of your project. - -### Step 4: View the Output in a Browser - -Open the `index.html` file in a web browser to see the output. You will see a `
` element with a background image positioned at the top right corner of the background area. - - -
-

- This is a div with a background image positioned at the top right corner. -

-
-
- -By following these steps, you can use the `background-position` property to position the background image of an element at the top right corner of the background area. - -## Conclusion - -The `background-position` property in CSS allows you to control the placement of the background image within the background area of an element. By specifying the position using keywords, percentages, or length values, you can create visually appealing designs by positioning the background image as desired. \ No newline at end of file diff --git a/docs/css/backgrounds/background-image/background-repeat.md b/docs/css/backgrounds/background-image/background-repeat.md deleted file mode 100644 index 4bc8049b4..000000000 --- a/docs/css/backgrounds/background-image/background-repeat.md +++ /dev/null @@ -1,137 +0,0 @@ ---- -id: background-repeat -title: Background Repeat -sidebar_label: Background Repeat -sidebar_position: 2 -tags: [background, css background, background repeat, background-repeat property] -description: Learn how to control the repetition of a background image in CSS using the background-repeat property. -keywords: - [ - background repeat, - css background repeat, - background-repeat property, - css background-repeat, - ] ---- - -In CSS, the `background-repeat` property is used to specify how a background image is repeated within the background area of an element. This property allows you to control the repetition of the background image in both the horizontal and vertical directions. - - - -## Syntax - -The syntax for the `background-repeat` property is as follows: - -```css title="index.css" -selector { - background-repeat: value; -} -``` - -- `selector`: The element to which the background repeat is applied. -- `background-repeat`: The CSS property used to control the repetition of the background image. -- `value`: Specifies how the background image should be repeated. It can take one of the following values: - - `repeat`: The background image is repeated both horizontally and vertically to fill the background area. - - `repeat-x`: The background image is repeated horizontally to fill the background area. - - `repeat-y`: The background image is repeated vertically to fill the background area. - - `no-repeat`: The background image is displayed only once without any repetition. - - `initial`: Sets the background repeat to its default value. - - `inherit`: Inherits the background repeat value from the parent element. - -The default value of the `background-repeat` property is `repeat`. - -## Example - -In the following example, the `background-repeat` property is used to set the repetition of the background image of a `
` element to `repeat`, which repeats the background image both horizontally and vertically to fill the background area: - -```css title="index.css" -div { - background-image: url("path/to/background-image.jpg"); - background-repeat: repeat; -} -``` - -In the HTML code below, the CSS rule will apply the `repeat` background repeat to the background image of the `
` element: - -```html title="index.html" -
-

- This is a div with a background image that repeats both horizontally and vertically to fill the background area. -

-
-``` - -In this example, the background image will be repeated in both the horizontal and vertical directions to fill the background area of the `
` element. You can adjust the `background-repeat` property to control how the background image is repeated based on your design requirements. - - - -:::note Try it yourself - -Experiment with different values of the `background-repeat` property to see how the background image repetition changes. You can use values like `repeat-x`, `repeat-y`, and `no-repeat` to achieve different visual effects. - -::: - -## Example: Using `background-repeat` with `background-size` - -You can combine the `background-repeat` property with the `background-size` property to create more complex background image effects. For example, you can repeat a background image in one direction while scaling it to cover the background area. Here's an example: - -This example demonstrates the use of the `background-size` property to set the size of the background image of an element: - - - - -```html showLineNumbers - - - - - - Background Repeat Example - - - -
-

- This is a div with a background image that repeats horizontally and scales to cover the background area. -

-
- - -``` - -
- - -```css showLineNumbers {3} -div { - background-image: url("/assets/jpeg-image.jpg"); - background-repeat: repeat-x; - background-size: cover; -} - -p { - color: white; - font-size: 1.5rem; - text-align: center; - padding: 20px; -} -``` - - -
- -Now, you can see the output of the above code in the Browser Window like this: - - -

- This is a div with a background image that repeats horizontally and scales to cover the background area. -

-
- -In this example, the `background-repeat` property is set to `repeat-x`, which repeats the background image horizontally to fill the background area of the `
` element. The `background-size` property is set to `cover`, which scales the background image to cover the entire background area while maintaining its aspect ratio. - -By combining the `background-repeat` and `background-size` properties, you can create visually appealing background effects for your web pages. - -## Conclusion - -The `background-repeat` property in CSS allows you to control how a background image is repeated within the background area of an element. By setting the `background-repeat` property to different values like `repeat`, `repeat-x`, `repeat-y`, or `no-repeat`, you can achieve various background image repetition effects based on your design requirements. Experiment with different values of the `background-repeat` property to create visually interesting background patterns for your web pages. \ No newline at end of file diff --git a/docs/css/backgrounds/background-image/background-size.md b/docs/css/backgrounds/background-image/background-size.md deleted file mode 100644 index e71476390..000000000 --- a/docs/css/backgrounds/background-image/background-size.md +++ /dev/null @@ -1,134 +0,0 @@ ---- -id: background-size -title: Background Size -sidebar_label: Background Size -sidebar_position: 1 -tags: [background, css background, background size, background-size property] -description: Learn how to set the size of the background image of an element in CSS using the background-size property. -keywords: - [ - background size, - css background size, - background-size property, - css background-size, - ] ---- - -In CSS, the `background-size` property is used to specify the size of the background image of an element. This property allows you to control how the background image is displayed within the element's background area. - - - -## Syntax - -The syntax for the `background-size` property is as follows: - -```css title="index.css" -selector { - background-size: value; -} -``` - -- `selector`: The element to which the background size is applied. -- `background-size`: The CSS property used to set the size of the background image of an element. -- `value`: Specifies the size of the background image. It can take one of the following values: - - `auto`: The browser automatically scales the background image to its original size. - - `cover`: The background image is scaled to cover the entire background area, maintaining its aspect ratio. - - `contain`: The background image is scaled to fit within the background area while maintaining its aspect ratio. - - ``: Specifies the width and height of the background image using a length value (e.g., `200px`, `50%`). - - ``: Specifies the width and height of the background image as a percentage of the background area. - - `initial`: Sets the background size to its default value. - - `inherit`: Inherits the background size from the parent element. - -The default value of the `background-size` property is `auto`. - -## Example - -In the following example, the `background-size` property is used to set the size of the background image of a `
` element to `cover`, which scales the background image to cover the entire background area while maintaining its aspect ratio: - -```css title="index.css" -div { - background-image: url("path/to/background-image.jpg"); - background-size: cover; -} -``` - -In the HTML code below, the CSS rule will apply the `cover` background size to the background image of the `
` element: - -```html title="index.html" -
- This is a div with a background image that covers the entire background area. -
-``` - -By using the `background-size` property, you can control how the background image is displayed within the element's background area, allowing you to create visually appealing designs on your web page. - - - -:::tip additional information - -**Aspect Ratio**: The aspect ratio of an image is the ratio of its width to its height. When using the `cover` or `contain` values for the `background-size` property, the aspect ratio of the background image is maintained while scaling to fit the background area. - -**Length Values**: Length values (e.g., `200px`, `50%`) can be used to specify the width and height of the background image. When using length values, the background image is scaled to the specified dimensions. - -The `background-size` property is particularly useful when working with responsive web design, as it allows you to control how the background image adapts to different screen sizes and devices. -::: - -## Example for background-size property - -This example demonstrates the use of the `background-size` property to set the size of the background image of an element: - - - - -```html showLineNumbers - - - - - - Background Size Example - - - -
-

- Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed ac felis - sit amet nunc ultrices ultricies. Nullam nec nunc nec nunc ultrices - ultricies. Nullam nec nunc nec nunc ultrices ultricies. -

-
- - -``` - -
- - -```css showLineNumbers {3} -div { - background-image: url("/assets/jpeg-image.jpg"); - background-size: cover; - padding: 20px; - color: white; - text-align: center; -} -``` - - -
- -Now, you can see the output of the above code in the Browser Window like this: - - -

- Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed ac felis sit - amet nunc ultrices ultricies. Nullam nec nunc nec nunc ultrices ultricies. - Nullam nec nunc nec nunc ultrices ultricies. -

-
- -In this example, the `background-size` property is set to `cover`, which scales the background image to cover the entire background area of the `
` element while maintaining its aspect ratio. - -## Conclusion - -The `background-size` property in CSS allows you to control the size of the background image of an element, enabling you to create visually appealing designs on your web page. By specifying the size of the background image using values like `cover`, `contain`, or length values, you can customize how the background image is displayed within the background area of an element. \ No newline at end of file diff --git a/docs/css/box-model/_category_.json b/docs/css/box-model/_category_.json deleted file mode 100644 index 9ce7359bb..000000000 --- a/docs/css/box-model/_category_.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "label": "Box Model", - "position": 5, - "link": { - "type": "generated-index", - "description": "In this section, you will learn about the CSS Box Model. The CSS Box Model is a box that wraps around every HTML element. It consists of margins, borders, padding, and the actual content. The box model allows us to add a border around elements, and to define space between elements. The box model is used to create the layout design of a webpage." - } - } \ No newline at end of file diff --git a/docs/css/box-model/assets/BoxModelDiagram.css b/docs/css/box-model/assets/BoxModelDiagram.css deleted file mode 100644 index 8a533c160..000000000 --- a/docs/css/box-model/assets/BoxModelDiagram.css +++ /dev/null @@ -1,50 +0,0 @@ -.box-model-diagram { - display: flex; - align-items: center; - flex-direction: column; -} - -.box-model-diagram__margin { - background: #c2ba43c4; - border: 2px dashed #000; - padding: 10px; -} - -.box-model-diagram__margin:hover { - background: transparent; -} - -.box-model-diagram__border { - border: 2px solid #000; - margin: 10px; - padding: 10px 20px; - background: #9cf374; - color: #333; -} - -.box-model-diagram__border:hover { - background: #9cf374a8; -} - -.box-model-diagram__padding { - margin: 10px; - padding: 10px 20px; - border: 1px dashed #000; - background: #9fdbb8a8; - color: #333; -} - -.box-model-diagram__padding:hover { - background: #9fdbb8; -} - -.box-model-diagram__content { - margin: 10px; - padding: 10px 40px; - border: 1px solid #000; - background: #4edc89; -} - -.box-model-diagram__content:hover { - background: #4edc89a8; -} \ No newline at end of file diff --git a/docs/css/box-model/border-radius.md b/docs/css/box-model/border-radius.md deleted file mode 100644 index cd8426184..000000000 --- a/docs/css/box-model/border-radius.md +++ /dev/null @@ -1,140 +0,0 @@ ---- -id: border-radius -title: CSS Border Radius -sidebar_label: Border Radius -sidebar_position: 10 -keywords: - [ - css border radius, - border radius property, - css border radius property, - css rounded corners, - css border radius values, - css border radius shorthand, - ] -description: Learn how to use the CSS border-radius property to create rounded corners for elements in your web page layout. -tags: [css, border radius, css border radius, border radius property, css border radius property] ---- - -In CSS, the `border-radius` property is used to create rounded corners for elements in your web page layout. Rounded corners soften the appearance of elements and can make your web page design more visually appealing. By adjusting the `border-radius` values, you can control the curvature of the corners and create different styles for your elements. - - - -## Syntax - -The syntax for the `border-radius` property is as follows: - -```css title="index.css" -selector { - border-radius: value; -} -``` - -- `selector`: The element to which the border radius is applied. -- `border-radius`: The CSS property used to set the curvature of the corners of an element. -- `value`: Specifies the border radius values for the top-left, top-right, bottom-right, and bottom-left corners of the element. It can take one of the following forms: - - ``: Specifies a fixed radius value in pixels (e.g., `10px`). - - ``: Specifies the radius value as a percentage of the width or height of the element. - - `initial`: Sets the border radius to its default value. - - `inherit`: Inherits the border radius value from the parent element. - - `unset`: Resets the border radius to its inherited value if it inherits from its parent, or to its initial value if not. - - `none`: Specifies that no border radius is applied to the element. - - `initial`: Sets the border radius to its default value. - - `inherit`: Inherits the border radius value from the parent element. - - `unset`: Resets the border radius to its inherited value if it inherits from its parent, or to its initial value if not. -- `` or `` values can be specified for each corner individually in the following order: - - `border-radius: top-left top-right bottom-right bottom-left;` - - `border-radius: top-left/top-right bottom-right/bottom-left;` - - `border-radius: top-left/top-right/bottom-right/bottom-left;` - - `border-radius: top-left top-right/bottom-right bottom-left;` - -The default value of the `border-radius` property is `0`, which means the corners are square and have no curvature. - -## Example - -In the following example, the `border-radius` property is used to create a `
` element with rounded corners: - -```css title="index.css" -div { - border-radius: 10px; -} -``` - -In this example, the `border-radius` property sets the curvature of all four corners of the `
` element to `10px`, creating a rounded appearance for the element. You can adjust the `border-radius` value to create different levels of curvature for the corners of your elements. - -```html title="index.html" -
-``` - -In the HTML code above, the CSS rule will apply the specified `border-radius` value to the `
` element, resulting in rounded corners for the element. - -By using the `border-radius` property, you can create visually appealing designs with rounded corners for elements in your web page layout. Rounded corners can help soften the appearance of elements and add a touch of elegance to your web page design. - - - -:::note Try it yourself -Experiment with different values of the `border-radius` property to see how the curvature of the corners changes based on the specified radius values. -::: - -## Example for `border-radius` Property - -In the following example, the `border-radius` property is used to create a `
` element with rounded corners: - - - - -```html - - - - - - - Rounded Corners - - - -
-

This is a div with rounded corners.

-
- -``` - -
- - -```css -div { - border-radius: 10px; - background-color: lightblue; - padding: 20px; -} -``` - - -
- -Now, you can see the output of the above code in the Browser Window like this: - - -
-

- This is a div with rounded corners. -

-
-
- -In this example, the `border-radius` property is used to create rounded corners for the `
` element, giving it a softer appearance. The `border-radius` value of `10px` sets the curvature of the corners, creating a rounded effect for the element. - -By adjusting the `border-radius` value, you can control the level of curvature for the corners of elements in your web page layout. This allows you to customize the appearance of elements and create visually appealing designs with rounded corners. - -:::info Try it yourself - -You can experiment with different `border-radius` values to create various styles of rounded corners for elements in your web page layout. Try changing the `border-radius` value in the example above to see how it affects the curvature of the corners of the `
` element. -::: - -By following this example, you can use the `border-radius` property to create rounded corners for elements in your web page layout. Rounded corners can enhance the visual appeal of your design and add a touch of elegance to your web page elements. - -## Conclusion - -The `border-radius` property in CSS allows you to create rounded corners for elements in your web page layout. By setting the curvature of the corners using the `border-radius` property, you can soften the appearance of elements and create visually appealing designs with rounded corners. Experiment with different `border-radius` values to customize the curvature of the corners and create unique styles for your web page elements. \ No newline at end of file diff --git a/docs/css/box-model/border.md b/docs/css/box-model/border.md deleted file mode 100644 index e669a3c0a..000000000 --- a/docs/css/box-model/border.md +++ /dev/null @@ -1,136 +0,0 @@ ---- -id: border -title: CSS Border -sidebar_label: Border -sidebar_position: 9 -keywords: - [ - css border, - border property, - css border property, - css border styles, - css border width, - css border color, - css border shorthand, - border values, - ] -description: Learn how to use the CSS border property to create borders around elements in your web page layout. -tags: [css, border, css border, border property, css border property] ---- - -In CSS, the `border` property is used to create borders around elements in your web page layout. Borders are the lines that surround the content of an element and separate it from other elements on the page. By adjusting the border properties, you can control the appearance, style, width, and color of the borders to create visually appealing layouts. - - - -## Syntax - -The syntax for the `border` property is as follows: - -```css title="index.css" -selector { - border: value; -} -``` - -- `selector`: The element to which the border is applied. -- `border`: The CSS property used to set the border around an element. -- `value`: Specifies the border values for the style, width, and color of the border. It can take one of the following forms: - - ``: Specifies the style of the border (e.g., `solid`, `dashed`, `dotted`, `double`, etc.). - - ``: Specifies the width of the border in pixels, em, rem, etc. - - ``: Specifies the color of the border using a color name, hex code, RGB value, etc. - - `initial`: Sets the border to its default value. - - `inherit`: Inherits the border value from the parent element. - - `unset`: Resets the border to its inherited value if it inherits from its parent, or to its initial value if not. - -The `border` property can be set using one of the following shorthand values: - -- `border: value;`: Sets the same border style, width, and color for all four sides. -- `border: width style color;`: Sets the border width, style, and color for all four sides. -- `border: initial;`: Sets the border to its default value. -- `border: inherit;`: Inherits the border value from the parent element. -- `border: unset;`: Resets the border to its inherited value if it inherits from its parent, or to its initial value if not. -- `border-top: value;`: Sets the border style, width, and color for the top side. -- `border-right: value;`: Sets the border style, width, and color for the right side. -- `border-bottom: value;`: Sets the border style, width, and color for the bottom side. -- `border-left: value;`: Sets the border style, width, and color for the left side. -- `border-width: value;`: Sets the border width for all four sides. -- `border-style: value;`: Sets the border style for all four sides. -- `border-color: value;`: Sets the border color for all four sides. - -The default value of the `border` property is `none`, which means no border is applied to the element. - -## Example - -In the following example, the `border` property is used to set a solid border around a `
` element with a width of `2px` and a color of `red`: - -```css title="index.css" -div { - border: 2px solid red; -} -``` - -In this example, the border around the `
` element will have a solid style, a width of `2px`, and a color of `red`. You can customize the border style, width, and color to achieve the desired visual effect for your web page layout. - - - -:::note Note -The `border` property can be combined with other border-related properties such as `border-radius` to create more complex border effects like rounded corners. -::: - -## Example for border property - -### Example 1: Setting Border Style, Width, and Color - -In this example, we set the border style to `dashed`, the width to `3px`, and the color to `blue` for a `
` element: - - - - -```html title="index.html" - - - - - - CSS Border Example - - - -
-

This is a div element with a dashed border.

-
- - -``` - -
- - -```css title="styles.css" -div { - border: 3px dashed blue; -} -``` - - -
- -Now, you can see the output of the above code in the Browser Window like this: - - -
-

- This is a div element with a dashed border. -

-
-
- -By following this example, you can use the `border` property to create borders around elements in your web page layout. Adjusting the border style, width, and color allows you to customize the appearance of the borders to match your design requirements. - -:::info try it yourself -You can experiment with different border styles, widths, and colors to create unique border effects for your web page elements. Try changing the border properties in the example above to see how they affect the appearance of the border around the `
` element. -::: - -## Conclusion - -The `border` property in CSS is a powerful tool for creating borders around elements in your web page layout. By setting the border style, width, and color, you can control the appearance of the borders and enhance the visual appeal of your web pages. Experiment with different border styles and colors to create unique designs that make your content stand out. \ No newline at end of file diff --git a/docs/css/box-model/box-sizing.md b/docs/css/box-model/box-sizing.md deleted file mode 100644 index 223e0bb6c..000000000 --- a/docs/css/box-model/box-sizing.md +++ /dev/null @@ -1,160 +0,0 @@ ---- -id: box-sizing -title: CSS Box Sizing -sidebar_label: Box Sizing -sidebar_position: 2 -keywords: [css box sizing, box sizing, css box model, css box model box sizing] -description: Learn how the CSS `box-sizing` property can be used to control the sizing behavior of elements in the CSS box model. -tags: [css, box sizing, css box model, css box model box sizing] ---- - -In CSS, the `box-sizing` property is used to control the sizing behavior of elements in the CSS box model. By default, the size of an element is calculated based on its content area, padding, and border. However, the `box-sizing` property allows you to change this behavior and include the padding and border in the total width and height of the element. - - - -## Syntax - -The syntax for the `box-sizing` property is as follows: - -```css title="index.css" -selector { - box-sizing: value; -} -``` - -- `selector`: The element to which the box sizing is applied. -- `box-sizing`: The CSS property used to control the sizing behavior of the element. -- `value`: Specifies the sizing behavior of the element. It can take one of the following values: - - `content-box`: The default value. The width and height of the element are calculated based on the content area only. - - `border-box`: The width and height of the element include the padding and border, but not the margin. - -The default value of the `box-sizing` property is `content-box`. - -## Example - -In the following example, the `box-sizing` property is used to set the sizing behavior of a `
` element to `border-box`, which includes the padding and border in the total width and height of the element: - -```css title="index.css" -div { - box-sizing: border-box; - width: 200px; - padding: 20px; - border: 1px solid black; -} -``` - -In the HTML code below, the CSS rule will apply the `border-box` sizing behavior to the `
` element, resulting in a total width of `200px` including the padding and border: - -```html title="index.html" -
-``` - -In this example, the total width of the `
` element will be `200px`, including the padding and border, due to the `border-box` value of the `box-sizing` property. - - - -:::note Try it yourself -Experiment with different values of the `box-sizing` property to see how the sizing behavior of elements changes based on the box model. - -::: - -## Example for Box Sizing - -### Example 1: Using `content-box` - -In this example, the `box-sizing` property is set to `content-box`, which calculates the width and height of the element based on the content area only: - - - - -```html title="index.html" - - - - - Box Sizing Example - - -
- - -``` - -
- - -```css title="index.css" -div { - box-sizing: content-box; - width: 200px; - padding: 20px; - border: 1px solid black; -} -``` - - -
- -Now, you can see the output of the above code in the Browser Window like this: - - -
-
- -In this example, the total width of the `
` element will be `242px`, calculated as `200px` for the width, `20px` for the left padding, `20px` for the right padding, and `1px` for the left and right borders, due to the `content-box` value of the `box-sizing` property. - - - -### Example 2: Using `border-box` - -In this example, the `box-sizing` property is set to `border-box`, which includes the padding and border in the total width and height of the element: - - - - -```html title="index.html" - - - - - Box Sizing Example - - -
- - -``` - -
- - - -```css title="index.css" -div { - box-sizing: border-box; - width: 200px; - padding: 20px; - border: 1px solid black; -} -``` - - -
- -Now, you can see the output of the above code in the Browser Window like this: - - -
-
- -In this example, the total width of the `
` element will be `200px`, including the padding and border, due to the `border-box` value of the `box-sizing` property. - -By using the `box-sizing` property, you can control how the width and height of elements are calculated in the CSS box model, allowing you to create more predictable and consistent layouts in your web pages. - -:::tip -The `box-sizing` property is particularly useful when working with responsive web design, as it helps maintain the integrity of the layout when resizing elements or adjusting padding and borders. -::: - -## Conclusion - -The `box-sizing` property in CSS allows you to control the sizing behavior of elements in the CSS box model. By setting the `box-sizing` property to `border-box`, you can include the padding and border in the total width and height of an element, making it easier to create consistent and predictable layouts in your web pages. Experiment with different values of the `box-sizing` property to see how they affect the sizing of elements and improve the responsiveness of your web designs. \ No newline at end of file diff --git a/docs/css/box-model/intro.md b/docs/css/box-model/intro.md deleted file mode 100644 index 69204e9b6..000000000 --- a/docs/css/box-model/intro.md +++ /dev/null @@ -1,81 +0,0 @@ ---- -id: introdution -title: Introduction to the CSS Box Model -sidebar_label: Introduction -sidebar_position: 1 -keywords: [css box model, box model, css layout, css box model introduction] -description: Learn about the CSS box model and how it is used to layout elements on a web page. -tags: [css, box model, css layout, css box model introduction] ---- - -import BoxModelDiagram from './script/BoxModelDiagram'; - -In CSS, the **Box Model** is a fundamental concept that describes how elements are laid out on a web page. It consists of four main components: **content**, **padding**, **border**, and **margin**. Understanding the box model is essential for creating well-structured and visually appealing web layouts. - - - -The box model is used to calculate the size of an element, including its content area, padding, border, and margin. Each of these components plays a specific role in defining the layout and appearance of an element on the page. - -## Structure of the Box Model - -The box model can be visualized as a rectangular box that wraps around an element. The box consists of the following components: - - - -## Components of the Box Model - -The four components of the box model are as follows: - -1. **Content**: The content area is the innermost part of the box that contains the actual content of the element, such as text, images, or other media. -2. **Padding**: The padding is the space between the content area and the border. It provides additional space around the content, helping to create separation between the content and the border. -3. **Border**: The border is the outer edge of the box that surrounds the content and padding. It can be styled with different colors, widths, and styles to create visual effects. -4. **Margin**: The margin is the space outside the border that separates the element from other elements on the page. It provides spacing between elements, helping to control the layout of the page. -5. **Width and Height**: The width and height of an element are calculated based on the content area, padding, border, and margin. The total width of an element is the sum of the content width, padding, border, and margin. - -## Box Model Example - -Let's look at an example to illustrate how the box model works. Consider the following CSS code: - -```css title="styles.css" -.box { - width: 200px; - height: 100px; - padding: 20px; - border: 2px solid black; - margin: 10px; -} -``` - -In this example, we have defined a box with a width of `200px`, height of `100px`, padding of `20px`, border of `2px`, and margin of `10px`. - -The total width of the box can be calculated as follows: - -- Content width: `200px` -- Padding: `20px` (left) + `20px` (right) = `40px` -- Border: `2px` (left) + `2px` (right) = `4px` -- Margin: `10px` (left) + `10px` (right) = `20px` -- Total width: `200px` (content) + `40px` (padding) + `4px` (border) + `20px` (margin) = `264px` -- Total height: `100px` (content) + `40px` (padding) + `4px` (border) + `20px` (margin) = `164px` -- Total width and height of the box: `264px` x `164px` -- Total area of the box: `43,296px` -- Total perimeter of the box: `952px` - -By understanding the box model and how it works, you can create more effective and visually appealing web layouts. The box model is a powerful tool that allows you to control the size, spacing, and appearance of elements on a web page. - -In the next sections, we will explore each component of the box model in more detail and learn how to use them effectively in your CSS layouts. - - - -:::info Key Points - -- The CSS Box Model consists of four main components: **content**, **padding**, **border**, and **margin**. -- The box model is used to calculate the size of an element, including its content area, padding, border, and margin. -- Each component of the box model plays a specific role in defining the layout and appearance of an element on the page. -- Understanding the box model is essential for creating well-structured and visually appealing web layouts. -- The width and height of an element are calculated based on the content area, padding, border, and margin. - -::: - -## Conclusion - -The CSS Box Model is a fundamental concept that describes how elements are laid out on a web page. By understanding the box model and how it works, you can create more effective and visually appealing web layouts. Each component of the box model plays a specific role in defining the layout and appearance of an element on the page. In the next sections, we will explore each component of the box model in more detail and learn how to use them effectively in your CSS layouts. \ No newline at end of file diff --git a/docs/css/box-model/margin-callapse.md b/docs/css/box-model/margin-callapse.md deleted file mode 100644 index c23f2d0c8..000000000 --- a/docs/css/box-model/margin-callapse.md +++ /dev/null @@ -1,128 +0,0 @@ ---- -id: margin-callapse -title: "CSS Margin Collapse" -sidebar_label: "Margin Collapse" -sidebar_position: 8 -keywords: - - css margin collapse - - margin collapse - - css box model - - css box model margin collapse -description: Learn how CSS margin collapse works and how to prevent it in your web page layout. -tags: - - css - - margin collapse - - css margin collapse - - css box model - - css box model margin collapse ---- - -In CSS, margin collapse is a phenomenon where the vertical margins of adjacent elements collapse into a single margin. This can lead to unexpected spacing between elements and affect the layout of your web page. Understanding how margin collapse works and how to prevent it is essential for creating consistent and visually appealing layouts. - - - -## How Margin Collapse Works - -Margin collapse occurs when the top and bottom margins of adjacent elements touch or overlap. In this case, the margins collapse into a single margin that is equal to the larger of the two margins. This behavior is defined in the CSS specification and is a common occurrence in web page layouts. - -Here are some key points to keep in mind about margin collapse: - -- Margin collapse only occurs between adjacent elements. If there is a non-collapsible element (e.g., an element with a border, padding, or inline content) between two elements, the margins will not collapse. -- Margin collapse only affects vertical margins. Horizontal margins do not collapse. -- Margin collapse does not occur between a parent element and its first or last child element. The margins of the parent and child elements do not collapse in this case. -- Margin collapse does not occur between a parent element and an empty child element. The margins of the parent and empty child elements do not collapse. -- Margin collapse does not occur between floated elements. The margins of floated elements do not collapse with other elements. -- Margin collapse does not occur between absolutely positioned elements. The margins of absolutely positioned elements do not collapse with other elements. -- Margin collapse does not occur between elements with a fixed height. The margins of elements with a fixed height do not collapse with other elements. - -## How to Prevent Margin Collapse - -To prevent margin collapse and control the spacing between elements in your web page layout, you can use the following techniques: - -### 1. Adding Padding or Border - -One way to prevent margin collapse is to add padding or a border to the element. By adding padding or a border, you create a non-collapsible space between the element and its adjacent elements, preventing the margins from collapsing. - -```css title="index.css" -.element { - padding: 1px; -} -``` - -### 2. Using `display: inline-block` - -Another way to prevent margin collapse is to use the `display: inline-block` property on the element. When an element is displayed as an inline-block, its margins do not collapse with adjacent elements, providing more control over the spacing between elements. (for example, when you have a `div` element with class `element` and you want to prevent margin collapse) - -```css title="index.css" -.element { - display: inline-block; -} -``` - -### 3. Using `overflow: hidden` - -You can also prevent margin collapse by using the `overflow: hidden` property on the parent element. This property creates a new block formatting context for the parent element, preventing the margins of its child elements from collapsing with other elements. - -```css title="index.css" -.parent { - overflow: hidden; -} -``` - -By using these techniques, you can prevent margin collapse and control the spacing between elements in your web page layout. This allows you to create more consistent and visually appealing designs by managing the margins of adjacent elements effectively. - - - -:::note Try it yourself -Compare this snippet from [CSS Width and Height](/docs/css/box-model/width-height) to learn how to use the CSS `width` and `height` properties to control the dimensions of elements in your web page layout. -::: - -## Example for Margin Collapse - -In the following example, margin collapse occurs between two `
` elements with top and bottom margins. The margins collapse into a single margin, creating unexpected spacing between the elements: - - - - - ```html - - - - - - Margin Collapse Example - - - -
Element 1
-
Element 2
- - - ``` - -
- - ```css - .element { - margin: 20px; - background-color: lightblue; - padding: 10px; - } - ``` - -
- -Now, you can see the output of the above code in the Browser Window like this: - - -
Element 1
-
Element 2
-
- -In this example, the top and bottom margins of the two `
` elements collapse into a single margin, creating extra spacing between the elements. This can lead to unexpected layout issues and affect the visual appearance of your web page. - -By using the techniques mentioned above, you can prevent margin collapse and control the spacing between elements in your web page layout. This allows you to create more consistent and visually appealing designs by managing the margins of adjacent elements effectively. - -## Conclusion - -Margin collapse is a common phenomenon in CSS that can affect the spacing between elements in your web page layout. By understanding how margin collapse works and how to prevent it, you can create more consistent and visually appealing designs that provide a better user experience. \ No newline at end of file diff --git a/docs/css/box-model/margin.md b/docs/css/box-model/margin.md deleted file mode 100644 index 40ccdc664..000000000 --- a/docs/css/box-model/margin.md +++ /dev/null @@ -1,150 +0,0 @@ ---- -id: margin -title: CSS Margin -sidebar_label: Margin -sidebar_position: 3 -keywords: - [ - css margin, - margin property, - css margin property, - css spacing, - margin shorthand, - margin values, - ] -description: Learn how to use the CSS margin property to create space around elements in your web page layout. -tags: [css, margin, css margin, margin property, css margin property] ---- - -In CSS, the `margin` property is used to create space around elements in your web page layout. Margins are the transparent spaces outside the border of an element that separate it from other elements on the page. By adjusting the margin values, you can control the spacing between elements and create visually appealing layouts. - - - -## Syntax - -The syntax for the `margin` property is as follows: - -```css title="index.css" -selector { - margin: value; -} -``` - -- `selector`: The element to which the margin is applied. -- `margin`: The CSS property used to set the margin around an element. -- `value`: Specifies the margin values for the top, right, bottom, and left sides of the element. It can take one of the following forms: - - ``: Specifies a fixed margin value in pixels (e.g., `10px`). - - ``: Specifies a margin value as a percentage of the width of the containing element. - - `auto`: Adjusts the margin to automatically distribute the space between elements. - - `initial`: Sets the margin to its default value. - - `inherit`: Inherits the margin value from the parent element. - - `unset`: Resets the margin to its inherited value if it inherits from its parent, or to its initial value if not. - -The `margin` property can be set using one of the following shorthand values: - -- `margin: value;`: Sets the same margin value for all four sides. -- `margin: vertical horizontal;`: Sets the vertical margin (top and bottom) and horizontal margin (left and right) to different values. -- `margin: top right bottom left;`: Sets individual margin values for the top, right, bottom, and left sides. -- `margin: initial;`: Sets the margin to its default value. -- `margin: inherit;`: Inherits the margin value from the parent element. -- `margin: unset;`: Resets the margin to its inherited value if it inherits from its parent, or to its initial value if not. -- `margin-top: value;`: Sets the margin value for the top side. -- `margin-right: value;`: Sets the margin value for the right side. -- `margin-bottom: value;`: Sets the margin value for the bottom side. -- `margin-left: value;`: Sets the margin value for the left side. -- `margin-block-start: value;`: Sets the margin value for the block-start side (top margin in horizontal writing mode). -- `margin-block-end: value;`: Sets the margin value for the block-end side (bottom margin in horizontal writing mode). - -The default value of the `margin` property is `0`, which means no margin is applied to the element. - -## Example - -In the following example, the `margin` property is used to set the margin around a `
` element to `20px` on all sides: - -```css title="index.css" -div { - margin: 20px; -} -``` - -In the HTML code below, the CSS rule will apply the `20px` margin to the `
` element: - -```html title="index.html" -
This is a div element with a 20px margin around it.
-``` - -By adjusting the margin values, you can control the spacing between elements and create visually appealing layouts in your web page design. - - - -:::info Additional Information - -**Margin Values:** - -- Margins are the transparent spaces around elements that separate them from other elements on the page. -- The `margin` property is used to set the margin around an element. -- Margin values can be specified in pixels, percentages, or using the `auto`, `initial`, `inherit`, or `unset` keywords. -- The default value of the `margin` property is `0`, which means no margin is applied to the element. -- The `margin` property can be set using shorthand values or individual properties for each side. -- By adjusting the margin values, you can control the spacing between elements and create visually appealing layouts in your web page design. -- Margins are part of the CSS box model and are used to create space around elements in the layout. - -::: - -## Example for Margin - -Now, let's look at an example that demonstrates how the `margin` property can be used to create space around an element in a web page layout. - - - - -```html - - - - - - - Margin Example - - - -
-

- This is a div element with a 20px margin around it. -

-
- - -``` - -
- - - -```css -div { - margin: 20px; - padding: 10px; - border: 1px solid black; -} -``` - - -
- -Now, you can see the output of the above code in the Browser Window like this: - - -
-

- This is a div element with a 20px margin around it. -

-
-
- -By following this example, you can use the `margin` property to create space around an element in your web page layout. Adjusting the margin values allows you to control the spacing between elements and create visually appealing designs. - -## Conclusion - -The `margin` property in CSS is a powerful tool for creating space around elements in your web page layout. By setting the margin values for an element, you can control the spacing between elements and create visually appealing designs. Understanding how to use the `margin` property effectively will help you create well-structured and visually appealing web pages. \ No newline at end of file diff --git a/docs/css/box-model/max-width-height.md b/docs/css/box-model/max-width-height.md deleted file mode 100644 index 874631713..000000000 --- a/docs/css/box-model/max-width-height.md +++ /dev/null @@ -1,132 +0,0 @@ ---- -id: max-width-height -title: "CSS Max-Width and Max-Height" -sidebar_label: "Max-Width and Max-Height" -sidebar_position: 7 -keywords: - - css max-width - - css max-height - - max-width property - - max-height property - - css sizing - - css dimensions - - css box model - - css box model max-width - - css box model max-height -description: Learn how to use the CSS max-width and max-height properties to set the maximum dimensions of elements in your web page layout. -tags: - - css - - max-width - - max-height - - max-width property - - max-height property ---- - -In CSS, the `max-width` and `max-height` properties are used to set the maximum dimensions of elements in your web page layout. The `max-width` property specifies the maximum width of an element, while the `max-height` property specifies the maximum height of an element. By adjusting the `max-width` and `max-height` values, you can ensure that elements do not become larger than a certain size, even if their content is larger. - - - -## Syntax - -The syntax for the `max-width` and `max-height` properties is as follows: - -```css title="index.css" -selector { - max-width: value; - max-height: value; -} -``` - -- `selector`: The element to which the maximum width and height are applied. -- `max-width`: The CSS property used to set the maximum width of an element. -- `max-height`: The CSS property used to set the maximum height of an element. -- `value`: Specifies the maximum width and height values for the element. It can take one of the following forms: - - ``: Specifies a fixed maximum width or height value in pixels (e.g., `100px`). - - ``: Specifies the maximum width or height value as a percentage of the width or height of the containing element. - - `none`: Removes the maximum width or height restriction. - - `initial`: Sets the maximum width or height to its default value. - - `inherit`: Inherits the maximum width or height value from the parent element. - - `unset`: Resets the maximum width or height to its inherited value if it inherits from its parent, or to its initial value if not. - - `fit-content`: Specifies that the maximum width or height should be the minimum size needed to fit the content. - - `min-content`: Specifies that the maximum width or height should be the minimum size needed to fit the content, but not smaller than the `min-width` or `min-height` value. - -The default value of the `max-width` and `max-height` properties is `none`, which means there is no maximum width or height set for the element. - -## Example - -In the following example, the `max-width` and `max-height` properties are used to set the maximum dimensions of a `
` element to `300px` and `150px`, respectively: - -```css title="index.css" -div { - max-width: 300px; - max-height: 150px; -} -``` - -In this example, the `
` element will not grow larger than `300px` in width and `150px` in height, even if its content exceeds these dimensions. This can be useful when you want to prevent elements from expanding beyond a certain size in your layout. - -By using the `max-width` and `max-height` properties, you can control the maximum dimensions of elements in your web page layout and ensure that they do not become larger than a specified size. This can help you create more consistent and visually appealing designs by limiting the size of elements based on your design requirements. - - - -:::note Try it yourself -Experiment with different values of the `max-width` and `max-height` properties to see how the maximum dimensions of elements change based on the box model. -::: - -## Example for `max-width` and `max-height` - -In the following example, the `max-width` and `max-height` properties are used to set the maximum dimensions of a `
` element to `300px` and `150px`, respectively: - - - - -```html - - - - - - Max-Width and Max-Height Example - - - -
-

Max-Width and Max-Height Example with CSS

-
- - -``` - -
- - -```css -div { - max-width: 300px; - max-height: 150px; - background-color: lightblue; -} - -h1, p { - padding: 10px; -} -``` - - -
- -Now, you can see the output of the above code in the Browser Window like this: - - -
-

Max-Width and Max-Height Example with CSS

-
-
- -In this example, the `
` element will not grow larger than `300px` in width and `150px` in height, even if its content exceeds these dimensions. The `max-width` and `max-height` properties ensure that the element maintains a maximum size on the page, providing a consistent layout for your web page design. - -By experimenting with different values for the `max-width` and `max-height` properties, you can control the maximum dimensions of elements in your web page layout and create visually appealing designs that adapt to various screen sizes and content lengths. - -## Conclusion - -By using the `max-width` and `max-height` properties, you can set the maximum dimensions of elements in your web page layout, ensuring that they do not become larger than a specified size. This can help you create more consistent and visually appealing designs by limiting the size of elements based on your design requirements. Experiment with different values for the `max-width` and `max-height` properties to see how they affect the layout of your web page and how you can use them to control the dimensions of elements effectively. \ No newline at end of file diff --git a/docs/css/box-model/min-width-height.md b/docs/css/box-model/min-width-height.md deleted file mode 100644 index 9318aef96..000000000 --- a/docs/css/box-model/min-width-height.md +++ /dev/null @@ -1,138 +0,0 @@ ---- -id: min-width-height -title: "CSS Min-Width and Min-Height" -sidebar_label: "Min-Width and Min-Height" -sidebar_position: 6 -keywords: - - css min-width - - css min-height - - min-width property - - min-height property - - css sizing - - css dimensions - - css box model - - css box model min-width - - css box model min-height -description: Learn how to use the CSS min-width and min-height properties to set the minimum dimensions of elements in your web page layout. -tags: - - css - - min-width - - min-height - - min-width property - - min-height property ---- - -In CSS, the `min-width` and `min-height` properties are used to set the minimum dimensions of elements in your web page layout. The `min-width` property specifies the minimum width of an element, while the `min-height` property specifies the minimum height of an element. By adjusting the `min-width` and `min-height` values, you can ensure that elements do not become smaller than a certain size, even if their content is smaller. - - - -## Syntax - -The syntax for the `min-width` and `min-height` properties is as follows: - -```css title="index.css" -selector { - min-width: value; - min-height: value; -} -``` - -- `selector`: The element to which the minimum width and height are applied. -- `min-width`: The CSS property used to set the minimum width of an element. -- `min-height`: The CSS property used to set the minimum height of an element. -- `value`: Specifies the minimum width and height values for the element. It can take one of the following forms: - - ``: Specifies a fixed minimum width or height value in pixels (e.g., `100px`). - - ``: Specifies the minimum width or height value as a percentage of the width or height of the containing element. - - `auto`: Adjusts the minimum width or height automatically based on the content of the element. - - `initial`: Sets the minimum width or height to its default value. - - `inherit`: Inherits the minimum width or height value from the parent element. - - `unset`: Resets the minimum width or height to its inherited value if it inherits from its parent, or to its initial value if not. -- `fit-content`: Specifies that the minimum width or height should be the minimum size needed to fit the content. -- `min-content`: Specifies that the minimum width or height should be the minimum size needed to fit the content, but not smaller than the `min-width` or `min-height` value. -- `max-content`: Specifies that the minimum width or height should be the maximum size needed to fit the content, but not larger than the `max-width` or `max-height` value. - -The default value of the `min-width` and `min-height` properties is `auto`, which means there is no minimum width or height set for the element. - -## Example - -In the following example, the `min-width` and `min-height` properties are used to set the minimum dimensions of a `
` element to `100px` and `50px`, respectively: - -```css title="index.css" -div { - min-width: 100px; - min-height: 50px; -} -``` - -In this example, the `
` element will not become smaller than `100px` in width and `50px` in height, even if its content is smaller. This ensures that the element maintains a minimum size on the page. - -## Browser Support - -The `min-width` and `min-height` properties are supported in all major browsers, including - -| Browsers | ![Chrome](/browser-img/chrome.png) | ![Firefox](/browser-img/firefox.png) | ![Safari](/browser-img/safari.png) | ![Edge](/browser-img/edge.png) | ![Opera](/browser-img/opera.png) | -|----------|:----------------------------------:|:------------------------------------:|:----------------------------------:|:------------------------------:|:--------------------------------:| -| Versions | Latest | Latest | Latest | Latest | Latest | - -For more information on browser support, you can refer to the [MDN Web Docs](https://developer.mozilla.org/en-US/docs/Web/CSS/min-width) and [Can I use](https://caniuse.com/?search=min-width) websites. - -By using the `min-width` and `min-height` properties, you can ensure that elements in your web page layout maintain a minimum size, providing a better user experience and preventing content from becoming too small to read or interact with. - - - -:::info Additional Information -Compare this snippet from [CSS Width and Height](/docs/css/box-model/width-height) to learn how to use the CSS `width` and `height` properties to control the dimensions of elements in your web page layout. -::: - -## Example for `min-width` and `min-height` - -In the following example, the `min-width` and `min-height` properties are used to set the minimum dimensions of a `
` element to `200px` and `100px`, respectively: - - - - -```html - - - - - - Min-Width and Min-Height Example - - - -
This is a div element with a minimum width of 200px and a minimum height of 100px.
- - -``` - -
- - -```css -div { - min-width: 200px; - min-height: 100px; - background-color: lightblue; - padding: 10px; -} -``` - - -
- -Now, you can see the output of the above code in the Browser Window like this: - - -
- This is a div element with a minimum width of 200px and a minimum height of 100px. -
-
- -In this example, the `
` element will not become smaller than `200px` in width and `100px` in height, even if its content is smaller. The `min-width` and `min-height` properties ensure that the element maintains a minimum size on the page, providing a consistent layout for your web page design. - -By experimenting with different values for the `min-width` and `min-height` properties, you can control the minimum dimensions of elements in your web page layout and create visually appealing designs that adapt to various screen sizes and content lengths. - -## Conclusion - -In this guide, you learned how to use the CSS `min-width` and `min-height` properties to set the minimum dimensions of elements in your web page layout. By setting the `min-width` and `min-height` values, you can ensure that elements maintain a minimum size on the page, providing a better user experience and preventing content from becoming too small to read or interact with. Experiment with different values for the `min-width` and `min-height` properties to create visually appealing designs that adapt to various screen sizes and content lengths. \ No newline at end of file diff --git a/docs/css/box-model/padding.md b/docs/css/box-model/padding.md deleted file mode 100644 index 5b1dc1518..000000000 --- a/docs/css/box-model/padding.md +++ /dev/null @@ -1,156 +0,0 @@ ---- -id: padding -title: CSS Padding -sidebar_label: Padding -sidebar_position: 4 -keywords: - [ - css padding, - padding property, - css padding property, - css spacing, - padding shorthand, - padding values, - ] -description: Learn how to use the CSS padding property to create space inside elements in your web page layout. -tags: [css, padding, css padding, padding property, css padding property] ---- - -In CSS, the `padding` property is used to create space inside elements in your web page layout. Padding is the transparent space inside the border of an element that separates the content from the border. By adjusting the padding values, you can control the spacing between the content and the border of an element to create visually appealing layouts. - - - -## Syntax - -The syntax for the `padding` property is as follows: - -```css title="index.css" -selector { - padding: value; -} -``` - -- `selector`: The element to which the padding is applied. -- `padding`: The CSS property used to set the padding inside an element. -- `value`: Specifies the padding values for the top, right, bottom, and left sides of the element. It can take one of the following forms: - - ``: Specifies a fixed padding value in pixels (e.g., `10px`). - - ``: Specifies a padding value as a percentage of the width of the containing element. - - `initial`: Sets the padding to its default value. - - `inherit`: Inherits the padding value from the parent element. - - `unset`: Resets the padding to its inherited value if it inherits from its parent, or to its initial value if not. - -The `padding` property can be set using one of the following shorthand values: - -- `padding: value;`: Sets the same padding value for all four sides. -- `padding: vertical horizontal;`: Sets the vertical padding (top and bottom) and horizontal padding (left and right) to different values. -- `padding: top right bottom left;`: Sets individual padding values for the top, right, bottom, and left sides. -- `padding: initial;`: Sets the padding to its default value. -- `padding: inherit;`: Inherits the padding value from the parent element. -- `padding: unset;`: Resets the padding to its inherited value if it inherits from its parent, or to its initial value if not. -- `padding-top: value;`: Sets the padding value for the top side. -- `padding-right: value;`: Sets the padding value for the right side. -- `padding-bottom: value;`: Sets the padding value for the bottom side. -- `padding-left: value;`: Sets the padding value for the left side. - -The default value of the `padding` property is `0`, which means no padding is applied to the element. - -## Example - -In the following example, the `padding` property is used to set the padding inside a `
` element to `20px` on all sides: - -```css title="index.css" -div { - padding: 20px; -} -``` - -In the HTML code below, the CSS rule will apply the `20px` padding to the `
` element: - -```html title="index.html" -
-

- This is a div with 20px padding inside. -

-
-``` - -By adjusting the padding values, you can create space inside elements and control the spacing between the content and the border of an element in your web page layout. - - - -## Example for Padding - -In this example, we'll explore different ways to set padding values using the `padding` property. - -### Example 1: Using Fixed Padding Values - -In this example, the `padding` property is used to set fixed padding values for all four sides of a `
` element: - -```css title="index.css" -div { - padding: 10px; -} -``` - -In the HTML code below, the CSS rule will apply the `10px` padding to the `
` element: - -```html title="index.html" -
-

- This is a div with 10px padding on all sides. -

-
-``` - -### Example 2: Using Different Padding Values - -In this example, the `padding` property is used to set different padding values for the top, right, bottom, and left sides of a `
` element: - -```css title="index.css" -div { - padding: 10px 20px 15px 25px; -} -``` - -In the HTML code below, the CSS rule will apply the different padding values to the `
` element: - -```html title="index.html" -
-

- This is a div with different padding values on each side. -

-
-``` - -### Example 3: Using Percentage Padding Values - -In this example, the `padding` property is used to set percentage-based padding values for all four sides of a `
` element: - -```css title="index.css" -div { - padding: 5% 10% 7% 15%; -} -``` - -In the HTML code below, the CSS rule will apply the percentage-based padding values to the `
` element: - -```html title="index.html" -
-

- This is a div with percentage-based padding values on all sides. -

-
-``` - -By using different padding values, you can create visually appealing layouts with varying amounts of space inside elements in your web page design. - - - -:::note Try it yourself -Experiment with different padding values and combinations to see how the spacing inside elements changes based on the padding values applied. - -::: - -## Conclusion - -The `padding` property in CSS allows you to create space inside elements by specifying padding values for the top, right, bottom, and left sides of an element. By adjusting the padding values, you can control the spacing between the content and the border of an element, creating visually appealing layouts in your web page design. Experiment with different padding values to achieve the desired spacing and layout for your web page elements. \ No newline at end of file diff --git a/docs/css/box-model/script/BoxModelDiagram.jsx b/docs/css/box-model/script/BoxModelDiagram.jsx deleted file mode 100644 index 037412fda..000000000 --- a/docs/css/box-model/script/BoxModelDiagram.jsx +++ /dev/null @@ -1,26 +0,0 @@ -import React from 'react'; -import '../assets/BoxModelDiagram.css'; - -const BoxModelDiagram = () => { - return ( -
-
- Margin - {/* Border */} -
- Border - {/* Padding */} -
- Padding - {/* Content */} -
- Content -
-
-
-
-
- ); -} - -export default BoxModelDiagram; \ No newline at end of file diff --git a/docs/css/box-model/width-height.md b/docs/css/box-model/width-height.md deleted file mode 100644 index b9a1db42a..000000000 --- a/docs/css/box-model/width-height.md +++ /dev/null @@ -1,280 +0,0 @@ ---- -id: width-height -title: CSS Width and Height -sidebar_label: Width and Height -sidebar_position: 5 -keywords: - [ - css width, - css height, - width property, - height property, - css sizing, - css dimensions, - css box model, - css box model width, - css box model height, - ] -description: Learn how to use the CSS width and height properties to control the dimensions of elements in your web page layout. -tags: [css, width, height, css width, css height, width property, height property] ---- - -In CSS, the `width` and `height` properties are used to control the dimensions of elements in your web page layout. The `width` property specifies the width of an element, while the `height` property specifies the height of an element. By adjusting the `width` and `height` values, you can control the size of elements and create visually appealing layouts. - - - -## Syntax - -The syntax for the `width` and `height` properties is as follows: - -```css title="index.css" -selector { - width: value; - height: value; -} -``` - -- `selector`: The element to which the width and height are applied. -- `width`: The CSS property used to set the width of an element. -- `height`: The CSS property used to set the height of an element. -- `value`: Specifies the width and height values for the element. It can take one of the following forms: - - ``: Specifies a fixed width or height value in pixels (e.g., `100px`). - - ``: Specifies the width or height value as a percentage of the width or height of the containing element. - - `auto`: Adjusts the width or height automatically based on the content of the element. - - `initial`: Sets the width or height to its default value. - - `inherit`: Inherits the width or height value from the parent element. - - `unset`: Resets the width or height to its inherited value if it inherits from its parent, or to its initial value if not. - - `fit-content`: Specifies that the width or height should be the minimum size needed to fit the content. - - `min-content`: Specifies that the width or height should be the minimum size needed to fit the content, but not smaller than the `min-width` or `min-height` value. - - `max-content`: Specifies that the width or height should be the maximum size needed to fit the content, but not larger than the `max-width` or `max-height` value. - -The default value of the `width` and `height` properties is `auto`, which means the width and height are automatically calculated based on the content of the element. - -## Example - -In the following example, the `width` and `height` properties are used to set the dimensions of a `
` element to `200px` and `100px`, respectively: - -```css title="index.css" -div { - width: 200px; - height: 100px; - background-color: lightblue; -} -``` - -In the HTML code below, the CSS rule will apply the specified width and height values to the `
` element, resulting in a width of `200px` and a height of `100px`: - -```html title="index.html" -
-``` - -In this example, the `
` element will have a width of `200px` and a height of `100px`, as specified by the `width` and `height` properties. - - - -:::note Try it yourself -Experiment with different values of the `width` and `height` properties to see how the dimensions of elements change based on the box model. -::: - -## Example for Width and Height - -### Example 1: Setting Fixed Width and Height - -In this example, the `width` and `height` properties are set to fixed values of `200px` and `100px`, respectively: - - - - -```html - - - - - - Fixed Width and Height - - - -
- - -``` - -
- - -```css -div { - width: 200px; - height: 100px; - background-color: lightblue; -} -``` - - -
- -Now, you can see the output of the above code in the Browser Window like this: - - -
-
-
- -In this example, the `
` element will have a fixed width of `200px` and a fixed height of `100px`, resulting in a rectangular box with the specified dimensions. - - - -### Example 2: Using Percentage Values - -In this example, the `width` and `height` properties are set to percentage values of `50%` and `50%`, respectively: - - - - -```html - - - - - - - Percentage Width and Height - - - -
- - -``` - -
- - -```css -div { - width: 50%; - height: 50%; - background-color: lightblue; -} -``` - - -
- -Now, you can see the output of the above code in the Browser Window like this: - - -
-
-
- -In this example, the `
` element will have a width and height equal to `50%` of the width and height of the containing element, resulting in a square box that occupies half of the available space. - - - -### Example 3: Using `auto` Value - -In this example, the `width` and `height` properties are set to `auto`, which adjusts the dimensions of the element automatically based on its content: - - - - -```html - - - - - - Auto Width and Height - - - -
-

This is a div element with auto width and height.

-
- - -``` - -
- - -```css -div { - width: auto; - height: auto; - background-color: lightblue; -} -``` - - -
- -Now, you can see the output of the above code in the Browser Window like this: - - -
-

This is a div element with auto width and height.

-
-
- -In this example, the `
` element will automatically adjust its width and height based on the content inside it, resulting in a box that fits the content without any fixed dimensions. - - - -### Example 4: Using `min-content` and `max-content` - -In this example, the `width` property is set to `min-content` and the `height` property is set to `max-content`, which adjust the dimensions of the element based on the minimum and maximum size needed to fit the content: - - - - -```html - - - - - - Min and Max Content - - - -
-

This is a div element with min and max content width and height.

-
- - -``` - -
- - -```css -div { - width: min-content; - height: max-content; - background-color: lightblue; -} -``` - - -
- -Now, you can see the output of the above code in the Browser Window like this: - - -
-

This is a div element with min and max content width and height.

-
-
- -In this example, the `
` element will adjust its width to the minimum size needed to fit the content and its height to the maximum size needed to fit the content, resulting in a box that wraps around the content without any extra space. - - - -By following these examples, you can use the `width` and `height` properties to control the dimensions of elements in your web page layout. Adjusting the width and height values allows you to create visually appealing designs and responsive layouts that adapt to different screen sizes. - -## Conclusion - -In this guide, you learned how to use the CSS `width` and `height` properties to control the dimensions of elements in your web page layout. By setting the `width` and `height` values, you can adjust the size of elements and create visually appealing designs that enhance the user experience. Experiment with different values and combinations of the `width` and `height` properties to create responsive layouts that adapt to various screen sizes and devices. \ No newline at end of file diff --git a/docs/css/colors/_category_.json b/docs/css/colors/_category_.json deleted file mode 100644 index cc37574c5..000000000 --- a/docs/css/colors/_category_.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "label": "Colors", - "position": 3, - "link": { - "type": "generated-index", - "description": "In this section, you will learn about the CSS Colors. CSS colors are used to specify the color of the text, backgrounds, borders, and other elements on a web page. You can specify colors using different methods such as color names, HEX values, RGB values, HSL values, and more." - } - } \ No newline at end of file diff --git a/docs/css/colors/color-names.md b/docs/css/colors/color-names.md deleted file mode 100644 index a1bae0ec3..000000000 --- a/docs/css/colors/color-names.md +++ /dev/null @@ -1,200 +0,0 @@ ---- -id: color-names -title: Color Names -sidebar_label: Color Names -tags: [color, css, color-names] -description: Color names are predefined names for colors that can be used in CSS to style elements. -keywords: - [ - color names, - css color names, - css colors, - css color names list, - ] -sidebar_position: 1 ---- - -In CSS, color names are predefined names for colors that can be used to style elements. Color names provide an easy way to specify colors in CSS without having to remember the hexadecimal (hex) or RGB values of the colors. There are 147 color names that are supported by all major browsers, and they can be used to set the color of text, backgrounds, borders, and other CSS properties. - - - -## Syntax - -The syntax for using color names in CSS is as follows: - -```css title="index.css" -selector { - color: color-name; -} -``` - -- `selector`: The element to which the color is applied. -- `color`: The CSS property used to set the color of the text. -- `color-name`: The predefined name of the color. -- The color name is used to specify the color of the text, background, border, or other CSS properties. - -## Example - -In the following example, the color name `red` is used to set the color of the text to red: - -```css title="index.css" -h1 { - color: red; -} -``` - -In the HTML code below, the CSS rule will set the color of the `

` element to red: - -```html title="index.html" -

This is a heading

-``` - -:::info Additional Information - -- Color names provide an easy way to specify colors in CSS. -- There are 147 color names that are supported by all major browsers. -- Color names can be used to set the color of text, backgrounds, borders, and other CSS properties. -- Color names are case-insensitive, meaning you can use uppercase, lowercase, or a combination of both when specifying color names. -- Color names are an alternative to using hexadecimal (hex) or RGB values to specify colors in CSS. -- Color names are useful for quickly setting the color of elements without having to remember specific color codes. -- Color names are easy to remember and can be used to create visually appealing designs in CSS. -- Color names are supported by all major browsers and provide a consistent way to specify colors across different platforms. - -::: - - - -### List of Common Color Names - -Here are some common CSS color names: - -- **Basic Colors**: `red`, `blue`, `green`, `yellow`, `black`, `white`, `gray` -- **Shades of Red**: `darkred`, `firebrick`, `indianred`, `tomato`, `lightcoral` -- **Shades of Blue**: `dodgerblue`, `deepskyblue`, `skyblue`, `lightblue`, `steelblue` -- **Shades of Green**: `forestgreen`, `darkgreen`, `lightgreen`, `lime`, `darkolivegreen` -- **Other Colors**: `gold`, `silver`, `peachpuff`, `plum`, `chocolate`, `orchid`, `coral` - -You can use these color names in your CSS stylesheets to set the color of elements and create visually appealing designs. Color names provide a convenient way to specify colors in CSS and make it easier to work with colors in web development projects. - - - -### Example: Using Color Names - -In the following example, the color name `blue` is used to set the color of the text to blue: - - - -```html title="index.html" - - - - - - Color Names Example - - - -

Welcome to Color Names

-

This is an example of using color names in CSS.

- - -``` -
- -```css title="styles.css" -h1 { - color: blue; -} - -p { - color: darkred; -} -``` - - -
- -Now, you can see the output of the above code in the Browser Window like this: - - -
-

Welcome to Color Names

-

This is an example of using color names in CSS.

-
-
- -In this example, the color names `blue` and `darkred` are used to set the color of the `

` and `

` elements, respectively. The `

` element will have blue text, while the `

` element will have dark red text. - -Color names are a convenient way to specify colors in CSS and can be used to create visually appealing designs in web development projects. - - - -:::note Extra Information -**1. How many way to use color in CSS?** - - There are several ways to specify colors in CSS: - - Using color names: Predefined names for colors (e.g., `red`, `blue`, `green`). - - Using hexadecimal (hex) values: A six-digit code that represents the RGB values of a color (e.g., `#ff0000` for red). - - Using RGB values: An RGB color value is specified with the `rgb()` function, which takes three parameters (e.g., `rgb(255, 0, 0)` for red). - - Using RGBA values: An RGBA color value is specified with the `rgba()` function, which takes four parameters (e.g., `rgba(255, 0, 0, 0.5)` for red with 50% opacity). - - Using HSL values: An HSL color value is specified with the `hsl()` function, which takes three parameters (e.g., `hsl(0, 100%, 50%)` for red). - - Using HSLA values: An HSLA color value is specified with the `hsla()` function, which takes four parameters (e.g., `hsla(0, 100%, 50%, 0.5)` for red with 50% opacity). - -**2. What are the advantages of using color names in CSS?** - - - Color names provide an easy and intuitive way to specify colors in CSS. - - Color names are easy to remember and use, making it convenient to work with colors in web development projects. - - Color names are supported by all major browsers, ensuring consistent color rendering across different platforms. - - Color names can be used to set the color of text, backgrounds, borders, and other CSS properties. - - Color names are an alternative to using hexadecimal (hex) or RGB values to specify colors in CSS. - - Color names are useful for quickly setting the color of elements without having to remember specific color codes. - - Color names can be combined with other CSS properties to create visually appealing designs in web development projects. - -**3. Are color names case-sensitive in CSS?** - - - No, color names are case-insensitive in CSS, meaning you can use uppercase, lowercase, or a combination of both when specifying color names. - - For example, `red`, `RED`, and `Red` are all valid ways to specify the color red using the color name in CSS. - - Color names are not case-sensitive, so you can use any combination of uppercase and lowercase letters when specifying color names in CSS. - -**4. Can color names be used with other CSS properties?** - - - Yes, color names can be used with other CSS properties to style elements in web pages. - - Color names can be combined with properties like `background-color`, `border-color`, `text-decoration`, and more to create visually appealing designs. - - Color names can be used to set the color of text, backgrounds, borders, and other CSS properties in web development projects. - - By using color names with other CSS properties, you can customize the appearance of elements and create engaging user interfaces. - -**5. How many color names are supported in CSS?** - - - There are 147 color names that are supported by all major browsers in CSS. - - These color names provide a wide range of colors that can be used to style elements in web pages. - - Color names are a convenient way to specify colors in CSS and make it easier to work with colors in web development projects. - - Color names are supported by all major browsers, ensuring consistent color rendering across different platforms. - -**6. Can color names be used in combination with other color values in CSS?** - - - Yes, color names can be used in combination with other color values like hexadecimal (hex), RGB, RGBA, HSL, and HSLA values in CSS. - - Color names can be combined with other color values to create complex color schemes and gradients in web development projects. - - By using color names in combination with other color values, you can achieve a wide range of colors and effects in your CSS stylesheets. - - Color names provide a simple and intuitive way to work with colors in CSS and can be easily combined with other color values to create visually appealing designs. - -**7. Are color names supported by all browsers?** - - - Yes, color names are supported by all major browsers, including Chrome, Firefox, Safari, Edge, and Opera. - - Color names provide a consistent way to specify colors in CSS across different platforms and ensure that colors are rendered correctly in web pages. - - Color names are widely supported and can be used to set the color of text, backgrounds, borders, and other CSS properties in web development projects. - - By using color names, you can create visually appealing designs that are consistent across different browsers and devices. - -**8. How can color names be used to create visually appealing designs in CSS?** - - - Color names can be used to set the color of text, backgrounds, borders, and other CSS properties in web pages. - - By combining color names with other CSS properties like `background-color`, `border-color`, `text-decoration`, and more, you can create visually appealing designs. - - Color names provide a simple and intuitive way to work with colors in CSS and make it easy to create engaging user interfaces. - - Color names can be used to create color schemes, gradients, and effects that enhance the visual appeal of web pages. - - By using color names creatively in your CSS stylesheets, you can design attractive and user-friendly interfaces for your web development projects. - -::: - -By using color names in CSS, you can easily set the color of elements in your web pages and create visually appealing designs. Color names provide a simple and intuitive way to work with colors in CSS and are supported by all major browsers. - -## Conclusion - -Color names are predefined names for colors that can be used in CSS to style elements. By using color names, you can specify the color of text, backgrounds, borders, and other CSS properties without having to remember specific color codes. Color names provide a convenient way to work with colors in CSS and make it easier to create visually appealing designs in web development projects. \ No newline at end of file diff --git a/docs/css/colors/css/style.css b/docs/css/colors/css/style.css deleted file mode 100644 index c50ef89a2..000000000 --- a/docs/css/colors/css/style.css +++ /dev/null @@ -1,5 +0,0 @@ -.color-box { - width: 100px; - height: 100px; - display: inline-block; - } \ No newline at end of file diff --git a/docs/css/colors/hex.md b/docs/css/colors/hex.md deleted file mode 100644 index f8df82d40..000000000 --- a/docs/css/colors/hex.md +++ /dev/null @@ -1,180 +0,0 @@ ---- -id: hex -title: Hex Color Values -sidebar_label: Hex Color Values -tags: [color, hex, css color, hex color] -description: Hex color values are used to specify colors in CSS using hexadecimal notation. -keywords: - [ - hex color values, - css hex color values, - css color values, - hex color, - ] -sidebar_position: 3 ---- - -In CSS, hex color values are used to specify colors using hexadecimal notation. Hex color values are represented by a `#` character followed by a six-digit hexadecimal number. The hexadecimal number is composed of three pairs of digits, each pair representing the intensity of the red, green, and blue color channels, respectively. Hex color values allow you to specify a wide range of colors by adjusting the intensity of the red, green, and blue color channels. - - - -## Syntax - -The syntax for hex color values is as follows: - -```css title="index.css" -selector { - color: #RRGGBB; -} -``` - -- `selector`: The element to which the hex color value is applied. -- `color`: The CSS property used to specify the color of an element. -- `#`: The `#` character represents the hex color value. -- `RR`: The intensity of the red color channel (00 to FF). -- `GG`: The intensity of the green color channel (00 to FF). -- `BB`: The intensity of the blue color channel (00 to FF). - -:::info Additional Information -**1. Hexadecimal Notation:** Hex color values are represented using hexadecimal notation, which allows you to specify colors using a combination of numbers and letters. (0-9, A-F) - -**2. Color Channels:** Hex color values consist of three pairs of digits, each pair representing the intensity of the red, green, and blue color channels, respectively. - -**3. Wide Range of Colors:** Hex color values allow you to create a wide range of colors by adjusting the intensity of the red, green, and blue color channels. - -**4. Shortened Hex Values:** Hex color values can be shortened if the three pairs of digits are the same. For example, `#FF0000` can be shortened to `#F00` for red. - -**5. Transparency:** Hex color values can also include an additional pair of digits to represent the alpha channel for transparency. For example, `#RRGGBBAA` represents a color with transparency. - -**6. Browser Support:** Hex color values are widely supported by all modern web browsers. - -**7. Color Picker Tools:** There are online tools and color picker applications that allow you to choose colors and generate their corresponding hex values. - -By using hex color values, you can easily specify colors in CSS and create visually appealing designs for your web pages. - -::: - - - -## Example - -In the following example, the hex color value `#FF0000` is used to specify the color of a `

` element as red: - -```css title="index.css" -h1 { - color: #FF0000; /* Red color */ -} -``` - -In the HTML code below, the CSS rule will apply the red color to the `

` element: - -```html title="index.html" -

This is a red heading.

-``` - -By adjusting the hex color value, you can create different colors for your elements in CSS. Hex color values provide a convenient way to specify colors and customize the appearance of your web pages. - -## Hex Color Shorthand - -Hex color values can be shortened if the three pairs of digits are the same. For example, the hex color value `#FF0000` can be shortened to `#F00` for red. This shorthand notation allows you to specify colors more concisely and reduces the length of the hex color value. - -### Example - -In the following example, the hex color value `#F00` is used to specify the color of a `

` element as red: - -```css title="index.css" -p { - color: #F00; /* Red color */ -} -``` - -In the HTML code below, the CSS rule will apply the red color to the `

` element: - -```html title="index.html" -

This is a red paragraph.

-``` - -By using the shorthand notation for hex color values, you can write CSS code more efficiently and make it easier to specify colors in your stylesheets. - - - -## Transparency with Hex Color Values - -Hex color values can include an additional pair of digits to represent the alpha channel for transparency. The alpha channel specifies the opacity of the color, allowing you to create semi-transparent colors in CSS. Hex color values with transparency are represented by eight digits: `#RRGGBBAA`, where `AA` represents the alpha channel value. - -### Example - -In the following example, the hex color value `#FF0000CC` is used to specify a semi-transparent red color for a `
` element: - -```css title="index.css" -div { - background-color: #FF0000CC; /* Semi-transparent red color */ -} -``` - -In the HTML code below, the CSS rule will apply the semi-transparent red color to the background of the `
` element: - -```html title="index.html" -
This is a semi-transparent red div.
-``` - -By using hex color values with transparency, you can create visually appealing effects and overlay colors with varying levels of opacity in your web designs. - -## Example: Using Hex Color Values - -In the following example, hex color values are used to specify the colors of different elements in a web page: - - - - -```html title="index.html" - - - - - - Hex Color Values Example - - - -

This is a red heading.

-

This is a blue paragraph.

-
This is a semi-transparent green div.
- - -``` - -
- - -```css title="styles.css" -h1 { - color: #FF0000; /* Red color */ -} - -p { - color: #0000FF; /* Blue color */ -} - -div { - background-color: #00FF00AA; /* Semi-transparent green color */ -} -``` - -
- -Now, you can see the output of the above code in the Browser Window like this: - - -
-

This is a red heading.

-

This is a blue paragraph.

-
This is a semi-transparent green div.
-
-
- -In this example, the hex color values `#FF0000`, `#0000FF`, and `#00FF00AA` are used to specify the colors of the `

`, `

`, and `

` elements, respectively. The `

` element is styled with a red color, the `

` element with a blue color, and the `

` element with a semi-transparent green background color. - -## Conclusion - -Hex color values are a popular way to specify colors in CSS using hexadecimal notation. By using hex color values, you can create a wide range of colors by adjusting the intensity of the red, green, and blue color channels. Hex color values provide a convenient and efficient method for specifying colors in your stylesheets and customizing the appearance of your web pages. With the ability to include transparency, hex color values offer additional flexibility in creating visually appealing designs for your websites. \ No newline at end of file diff --git a/docs/css/colors/hsl.md b/docs/css/colors/hsl.md deleted file mode 100644 index 24a0fbb51..000000000 --- a/docs/css/colors/hsl.md +++ /dev/null @@ -1,142 +0,0 @@ ---- -id: hsl -title: HSL Color Values -sidebar_label: HSL Color Values -tags: [color, hsl, css color, hsl color] -description: HSL color values are used to specify colors in CSS using the hue, saturation, and lightness color channels. -keywords: - [ - hsl color values, - css hsl color values, - css color values, - hsl color, - ] -sidebar_position: 5 ---- - -import './css/style.css'; - -In CSS, HSL color values are used to specify colors using the hue, saturation, and lightness color channels. HSL color values are represented by the `hsl()` function, which takes three arguments: the hue, saturation, and lightness color channels. The hue channel is represented by an angle value between 0 and 360 degrees, where 0 represents red, 120 represents green, and 240 represents blue. The saturation and lightness channels are represented by percentage values between 0% and 100%, where 0% represents no color saturation or lightness and 100% represents full color saturation or lightness. - - - -## Syntax - -The syntax for HSL color values is as follows: - -```css title="index.css" -selector { - color: hsl(hue, saturation, lightness); -} -``` - -- `selector`: The element to which the HSL color value is applied. -- `color`: The CSS property used to specify the color of an element. -- `hsl()`: The function used to specify HSL color values. -- `hue`: The color hue (0 to 360 degrees). -- `saturation`: The color saturation (0% to 100%). -- `lightness`: The color lightness (0% to 100%). - -## Example - -In the following example, the `hsl()` function is used to specify the color of a `
` element using HSL color values: - -```css title="index.css" -div { - color: hsl(120, 100%, 50%); /* Green color with 50% lightness */ -} -``` - -In the HTML code below, the CSS rule will apply the green color with 50% lightness to the `
` element: - -```html title="index.html" -
This is a green div.
-``` - - - -:::info Additional Information - -- HSL color values are represented by the `hsl()` function in CSS. -- HSL color values are specified using the hue, saturation, and lightness color channels. -- The hue channel is represented by an angle value between 0 and 360 degrees. -- The saturation and lightness channels are represented by percentage values between 0% and 100%. -- HSL color values provide a more intuitive way to specify colors based on their hue, saturation, and lightness. -- HSL color values are often used in web design for their ease of use and readability. -- HSL color values can be used in combination with other color functions and formats in CSS. -- HSL color values can be used to create a wide range of colors by adjusting the hue, saturation, and lightness values. - -::: - -## Example with HSL Color - -In the following example, we will create a color palette using HSL color values to generate a range of colors with varying hues, saturations, and lightness levels: - - - - -```html title="index.html" - - - - - - HSL Color Palette - - - -
-
-
-
-
-
-
-
-
-
-
-
- - -``` - -
- - -```css title="styles.css" -.color-box { - width: 100px; - height: 100px; - display: inline-block; -} -``` - - -
- -Now, you can see the output of the above code in the Browser Window like this: - - -
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- -In the HTML code above, we have created a color palette using HSL color values to generate a range of colors with varying hues. Each `
` element represents a color box with a different hue value ranging from 0 to 330 degrees. The saturation and lightness values are set to 100% and 50%, respectively, to maintain consistent saturation and lightness levels across the color palette. - - -## Conclusion - -HSL color values provide a flexible and intuitive way to specify colors in CSS based on their hue, saturation, and lightness. By using HSL color values, you can create visually appealing designs with a wide range of colors and easily adjust the hue, saturation, and lightness levels to achieve the desired color effects. HSL color values are widely supported by all modern web browsers and are commonly used in web design for their ease of use and readability. By mastering HSL color values, you can enhance your web design skills and create stunning color palettes for your web projects. diff --git a/docs/css/colors/hsla.md b/docs/css/colors/hsla.md deleted file mode 100644 index 62eb197e3..000000000 --- a/docs/css/colors/hsla.md +++ /dev/null @@ -1,142 +0,0 @@ ---- -id: hsla -title: HSLA Color Values -sidebar_label: HSLA Color Values -tags: [color, hsla, css color, hsla color] -description: HSLA color values are used to specify colors in CSS using the hue, saturation, lightness, and alpha color channels. -keywords: - [ - hsla color values, - css hsla color values, - css color values, - hsla color, - ] -sidebar_position: 6 ---- - -In CSS, HSLA color values are used to specify colors using the hue, saturation, lightness, and alpha color channels. HSLA color values are represented by the `hsla()` function, which takes four arguments: the hue, saturation, lightness, and alpha color channels. The hue channel is represented by an angle value between 0 and 360 degrees, where 0 represents red, 120 represents green, and 240 represents blue. The saturation and lightness channels are represented by percentage values between 0% and 100%, where 0% represents no color saturation or lightness and 100% represents full color saturation or lightness. The alpha channel is represented by a decimal value between 0 and 1, where 0 represents full transparency and 1 represents full opacity. - - - -## Syntax - -The syntax for HSLA color values is as follows: - -```css title="index.css" -selector { - color: hsla(hue, saturation, lightness, alpha); -} -``` - -- `selector`: The element to which the HSLA color value is applied. -- `color`: The CSS property used to specify the color of an element. -- `hsla()`: The function used to specify HSLA color values. -- `hue`: The color hue (0 to 360 degrees). -- `saturation`: The color saturation (0% to 100%). -- `lightness`: The color lightness (0% to 100%). -- `alpha`: The transparency of the color (0 to 1). - -## Example - -In the following example, the `hsla()` function is used to specify the color of a `
` element using HSLA color values with partial transparency: - -```css title="index.css" -div { - color: hsla(240, 100%, 50%, 0.5); /* Blue color with 50% transparency */ -} -``` - -In the HTML code below, the CSS rule will apply the blue color with 50% transparency to the `
` element: - -```html title="index.html" -
This is a partially transparent blue div.
-``` - -By using HSLA color values, you can create visually appealing color schemes with varying levels of transparency in your web designs. - - - -:::info Additional Information - -**HSLA Color Values:** - -- HSLA color values are represented by the `hsla()` function in CSS. -- HSLA color values are specified using the hue, saturation, lightness, and alpha color channels. -- The hue channel is represented by an angle value between 0 and 360 degrees. -- The saturation and lightness channels are represented by percentage values between 0% and 100%. -- The alpha channel is represented by a decimal value between 0 and 1. - -**Benefits of HSLA Color Values:** - -- HSLA color values allow you to create colors with varying levels of transparency. -- HSLA color values provide a flexible way to specify colors based on hue, saturation, lightness, and alpha values. -- HSLA color values are useful for creating visually appealing designs with semi-transparent elements. -- HSLA color values can be combined with other CSS properties to create unique color effects. -- HSLA color values are well-supported in modern web browsers. - -By using HSLA color values, you can enhance the visual appearance of your web pages and create engaging user experiences. -::: - -## Example: Using HSLA Color Values - -In the following example, HSLA color values are used to specify the colors of different elements in a web page: - - - - -```html title="index.html" - - - - - - HSLA Color Values Example - - - -

This is a semi-transparent blue heading.

-

This is a semi-transparent green paragraph.

-
This is a semi-transparent red div.
- - -``` - -
- - -```css title="styles.css" -h1 { - color: hsla(240, 100%, 50%, 0.5); /* Blue color with 50% transparency */ -} - -p { - color: hsla(120, 100%, 50%, 0.5); /* Green color with 50% transparency */ -} - -div { - color: hsla(0, 100%, 50%, 0.5); /* Red color with 50% transparency */ -} -``` - - -
- -Now, you can see the output of the above code in the Browser Window like this: - - -<> -

This is a semi-transparent blue heading.

-

This is a semi-transparent green paragraph.

-
This is a semi-transparent red div.
- -
- -In the example above, HSLA color values are used to specify the colors of the `

`, `

`, and `

` elements with varying hues and partial transparency. By adjusting the hue, saturation, lightness, and alpha values, you can create visually appealing color combinations for different elements on your web page. - -By using HSLA color values, you can enhance the visual appearance of your web designs and create engaging color schemes with varying levels of transparency. HSLA color values provide a flexible way to specify colors based on hue, saturation, lightness, and alpha values, allowing you to create unique color effects and visually appealing designs in your web projects. - -If you want to learn more about CSS colors, you can check out our [CSS Colors](/docs/category/colors) guide for additional information on color models, color functions, and color formats in CSS. - -## Conclusion - -HSLA color values are a powerful tool in CSS that allow you to create visually appealing designs with elements that have varying levels of transparency. By using the hue, saturation, lightness, and alpha color channels, you can create colors with precise levels of transparency to achieve the desired visual effect. HSLA color values are widely supported by all modern web browsers and are commonly used in web design to create gradient backgrounds, text shadows, and other visual effects. By mastering HSLA color values, you can enhance the visual appearance of your web pages and create engaging user experiences with unique color schemes and effects. \ No newline at end of file diff --git a/docs/css/colors/rgb.md b/docs/css/colors/rgb.md deleted file mode 100644 index 7c346da49..000000000 --- a/docs/css/colors/rgb.md +++ /dev/null @@ -1,131 +0,0 @@ ---- -id: rgb -title: RGB Color Values -sidebar_label: RGB Color Values -tags: [color, rgb, css color, rgb color] -description: RGB color values are used to specify colors in CSS using the red, green, and blue color channels. -keywords: - [ - rgb color values, - css rgb color values, - css color values, - rgb color, - ] -sidebar_position: 2 ---- - -In CSS, RGB color values are used to specify colors using the red, green, and blue color channels. RGB color values are represented by the `rgb()` function, which takes three arguments: the red, green, and blue color channels. Each color channel is represented by an integer value between 0 and 255, where 0 represents no color and 255 represents the maximum intensity of the color channel. - - - -## Syntax - -The syntax for RGB color values is as follows: - -```css title="index.css" -selector { - color: rgb(red, green, blue); -} -``` - -- `selector`: The element to which the RGB color value is applied. -- `color`: The CSS property used to specify the color of an element. -- `rgb()`: The function used to specify RGB color values. -- `red`: The intensity of the red color channel (0 to 255). -- `green`: The intensity of the green color channel (0 to 255). -- `blue`: The intensity of the blue color channel (0 to 255). - -## Example - -In the following example, the `rgb()` function is used to specify the color of a `
` element using RGB color values: - -```css title="index.css" -div { - color: rgb(255, 0, 0); /* Red color */ -} -``` - -In the HTML code below, the CSS rule will apply the red color to the `
` element: - -```html title="index.html" -
This is a red div.
-``` - -:::info Additional Information - -- RGB color values are represented by the `rgb()` function in CSS. -- RGB color values are specified using the red, green, and blue color channels. -- Each color channel is represented by an integer value between 0 and 255. -- RGB color values allow you to create a wide range of colors by adjusting the intensity of the red, green, and blue color channels. - -::: - -## RGB Color Channels - -The RGB color model uses three color channels—red, green, and blue—to create a wide range of colors. Each color channel has an intensity value between 0 and 255, where 0 represents no color and 255 represents the maximum intensity of the color channel. By combining different intensities of the red, green, and blue color channels, you can create millions of unique colors. - -### Red Color Channel - -The red color channel controls the intensity of red in the color. A value of 0 indicates no red color, while a value of 255 represents the maximum intensity of red. - -### Green Color Channel - -The green color channel controls the intensity of green in the color. A value of 0 indicates no green color, while a value of 255 represents the maximum intensity of green. - -### Blue Color Channel - -The blue color channel controls the intensity of blue in the color. A value of 0 indicates no blue color, while a value of 255 represents the maximum intensity of blue. - -By adjusting the intensity of each color channel, you can create a wide variety of colors in the RGB color model. - - - -## Example: Using RGB Color Values - -In the following example, the `rgb()` function is used to specify the color of a `` element using RGB color values: - - - - -```html title="index.html" - - - - - - RGB Color Example - - - - This is red text. - - -``` - - - - -```css title="styles.css" -span.red-text { - color: rgb(255, 0, 0); /* Red color */ -} -``` - - - - -Now, you can see the output of the above code in the Browser Window like this: - - -
- This is red text. -
-
- -In this example, the `rgb(255, 0, 0)` value is used to specify the color of the `` element as red. The text inside the `` element is displayed in red color on the web page. - -RGB color values are commonly used in CSS to specify colors for text, backgrounds, borders, and other elements on a web page. By adjusting the intensity of the red, green, and blue color channels, you can create a wide range of colors to style your web pages. - -## Conclusion - -RGB color values are a fundamental part of CSS that allow you to specify colors using the red, green, and blue color channels. By adjusting the intensity of each color channel, you can create millions of unique colors to style your web pages. RGB color values are versatile and widely used in web development to create visually appealing designs and user interfaces. \ No newline at end of file diff --git a/docs/css/colors/rgba.md b/docs/css/colors/rgba.md deleted file mode 100644 index 0b4f07fb6..000000000 --- a/docs/css/colors/rgba.md +++ /dev/null @@ -1,133 +0,0 @@ ---- -id: rgba -title: RGBA Color Values -sidebar_label: RGBA Color Values -tags: [color, rgba, css color, rgba color] -description: RGBA color values are used to specify colors in CSS using the red, green, blue, and alpha color channels. -keywords: - [ - rgba color values, - css rgba color values, - css color values, - rgba color, - ] -sidebar_position: 4 ---- - -In CSS, RGBA color values are used to specify colors using the red, green, blue, and alpha color channels. RGBA color values are represented by the `rgba()` function, which takes four arguments: the red, green, blue, and alpha color channels. The red, green, and blue color channels are represented by integer values between 0 and 255, where 0 represents no color and 255 represents the maximum intensity of the color channel. The alpha channel is represented by a decimal value between 0 and 1, where 0 represents full transparency and 1 represents full opacity. - - - -## Syntax - -The syntax for RGBA color values is as follows: - -```css title="index.css" -selector { - color: rgba(red, green, blue, alpha); -} -``` - -- `selector`: The element to which the RGBA color value is applied. -- `color`: The CSS property used to specify the color of an element. -- `rgba()`: The function used to specify RGBA color values. -- `red`: The intensity of the red color channel (0 to 255). -- `green`: The intensity of the green color channel (0 to 255). -- `blue`: The intensity of the blue color channel (0 to 255). -- `alpha`: The transparency of the color (0 to 1). - -## Example - -In the following example, the `rgba()` function is used to specify the color of a `
` element using RGBA color values with partial transparency: - -```css title="index.css" -div { - color: rgba(255, 0, 0, 0.5); /* Red color with 50% transparency */ -} -``` - -In the HTML code below, the CSS rule will apply the red color with 50% transparency to the `
` element: - -```html title="index.html" -
This is a partially transparent red div.
-``` - -:::info Additional Information - -- RGBA color values are represented by the `rgba()` function in CSS. -- RGBA color values are specified using the red, green, blue, and alpha color channels. -- The red, green, and blue color channels are represented by integer values between 0 and 255. -- The alpha channel is represented by a decimal value between 0 and 1. -- RGBA color values allow you to create colors with varying levels of transparency. -- RGBA color values are widely supported by all modern web browsers. - -::: - -## RGBA Color Channels - -The RGBA color model is an extension of the RGB color model that includes an additional alpha channel for transparency. The alpha channel specifies the opacity of the color, allowing you to create colors with varying levels of transparency. The alpha channel is represented by a decimal value between 0 and 1, where 0 represents full transparency and 1 represents full opacity. - -The RGBA color model is commonly used in web design to create visually appealing designs with elements that have varying levels of transparency. - - - -## Example with Gradient Background - -In the following example, the `rgba()` function is used to create a gradient background for a `
` element with varying levels of transparency: - - - - -```html title="index.html" - - - - - - RGBA Gradient Background Example - - - -
This is a gradient background with transparency.
- - -``` - -
- - -```css title="styles.css" -div { - background: linear-gradient(rgba(255, 0, 0, 1), rgba(255, 0, 0, 0)); - color: white; - padding: 20px; - text-align: center; -} -``` - - -
- -Now, you can see the output of the above code in the Browser Window like this: - - -
- This is a gradient background with transparency. -
-
- -In this example, the `linear-gradient()` function is used to create a gradient background that transitions from a fully opaque red color at the top to a fully transparent red color at the bottom of the `
` element. - -:::info Additional Information - -- The `linear-gradient()` function is used to create a gradient background in CSS. -- The `rgba()` function is used to specify colors with varying levels of transparency. -- The `linear-gradient()` function can be used to create gradients with multiple color stops and directions. -- The `rgba()` function allows you to create visually appealing designs with elements that have varying levels of transparency. -- The RGBA color model is widely supported by all modern web browsers. - -::: - -## Conclusion - -RGBA color values are a powerful tool in CSS that allow you to create visually appealing designs with elements that have varying levels of transparency. By using the red, green, blue, and alpha color channels, you can create colors with precise levels of transparency to achieve the desired visual effect. RGBA color values are widely supported by all modern web browsers and are commonly used in web design to create gradient backgrounds, text shadows, and other visual effects. \ No newline at end of file diff --git a/docs/css/fonts-and-text-properties/_category_.json b/docs/css/fonts-and-text-properties/_category_.json deleted file mode 100644 index f95fc456e..000000000 --- a/docs/css/fonts-and-text-properties/_category_.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "label": "Fonts and Text Properties", - "position": 9, - "link": { - "type": "generated-index", - "description": "In this section, you will learn about the CSS Fonts and Text Properties. CSS Fonts and Text Properties are used to style the text content of an element. You can specify the font size, font family, font style, font weight, text color, text alignment, text decoration, text transformation, and more." - } - } \ No newline at end of file diff --git a/docs/css/fonts-and-text-properties/font-align.md b/docs/css/fonts-and-text-properties/font-align.md deleted file mode 100644 index 694fcb636..000000000 --- a/docs/css/fonts-and-text-properties/font-align.md +++ /dev/null @@ -1,296 +0,0 @@ ---- -id: font-align -title: "CSS Font Alignment" -sidebar_label: "Font Alignment" -sidebar_position: 8 -tags: ["css", "font alignment", "css font alignment", "css text alignment", "css text properties"] -description: Learn how to use the CSS `text-align` property to align text within a container on your web page. -keywords: - - css text alignment - - css text align - - css text alignment property - - css text alignment values - - css text alignment examples ---- - -In CSS, the `text-align` property is used to specify the horizontal alignment of text within a container. It allows you to control the positioning of text elements on your web page, aligning them to the left, right, center, or justified within their containing block. - - - -The `text-align` property accepts several values that determine the alignment of text. By using this property, you can create visually appealing layouts by aligning text elements according to your design requirements. - -## Syntax - -The `text-align` property in CSS has the following syntax: - -```css title="index.css" -selector { - text-align: value; -} -``` - -- `selector`: The CSS selector that targets the text element you want to align. -- `value`: A keyword value that specifies the horizontal alignment of the text. The `text-align` property accepts the following values: - - `left`: Aligns the text to the left. - - `right`: Aligns the text to the right. - - `center`: Centers the text horizontally. - - `justify`: Stretches the lines of text so that each line has equal width, except for the last line. - - `start`: Aligns the text to the start of the line, based on the text direction. - - `end`: Aligns the text to the end of the line, based on the text direction. - - `inherit`: Inherits the text alignment from the parent element. - -Using these values, you can control the alignment of text elements within their containing block, ensuring that they are positioned correctly according to your layout requirements. - -## Examples - -### 1. Aligning Text to the Center - -You can use the `text-align` property to center-align text within a container. In the following example, we center-align a heading element: - - - - ```html - - - - - - Centered Text - - - -

Centered Heading

- - - ``` -
- - ```css - .centered { - text-align: center; - } - ``` - -
- - -

Centered Heading

-
- -:::info Informaton - -The `text-align` property can be applied to various text elements, such as headings, paragraphs, and spans, to create different visual styles. - -::: - - - -### 2. Justifying Text - -You can use the `text-align` property with the `justify` value to justify-align text within a container. In the following example, we justify-align a paragraph element: - - - - ```html - - - - - - Justified Text - - - -

This is a paragraph with justified text. Justified text stretches the lines so that each line has equal width.

- - - ``` -
- - ```css - .justified { - text-align: justify; - } - ``` - -
- - -

This is a paragraph with justified text. Justified text stretches the lines so that each line has equal width.

-
- -### 3. Aligning Text to the Right - -You can use the `text-align` property with the `right` value to right-align text within a container. In the following example, we right-align a paragraph element: - - - - ```html - - - - - - Right-Aligned Text - - - -

This is a paragraph with right-aligned text.

- - - ``` -
- - ```css - .right-aligned { - text-align: right; - } - ``` - -
- - -

This is a paragraph with right-aligned text.

-
- -:::note try it yourself - -Experiment with different text alignment values to see how they affect the layout of text elements on your web page. - -::: - - - -### 4. Aligning Text to the Left - -You can use the `text-align` property with the `left` value to left-align text within a container. In the following example, we left-align a paragraph element: - - - - ```html - - - - - - Left-Aligned Text - - - -

This is a paragraph with left-aligned text.

- - - ``` -
- - ```css - .left-aligned { - text-align: left; - } - ``` - -
- - -

This is a paragraph with left-aligned text.

-
- -### 5. Aligning Text Based on Text Direction - -You can use the `text-align` property with the `start` and `end` values to align text based on the text direction. In the following example, we align a paragraph element to the start and end of the line: - - - - ```html - - - - - - Text Alignment Based on Text Direction - - - -

This is a paragraph with text aligned to the start.

-

This is a paragraph with text aligned to the end.

- - - ``` -
- - ```css - .start-aligned { - text-align: start; - } - - .end-aligned { - text-align: end; - } - ``` - -
- - - <> -

This is a paragraph with text aligned to the start.

-

This is a paragraph with text aligned to the end.

- -
- -:::note try it yourself - -Experiment with different text alignment values to see how they affect the layout of text elements on your web page. - -::: - -### 6. Inheriting Text Alignment - -You can use the `text-align` property with the `inherit` value to inherit the text alignment from the parent element. In the following example, we inherit the text alignment for a paragraph element: - - - - ```html - - - - - - Inherited Text Alignment - - - -
-

This text inherits the alignment from the parent.

-
- - - ``` -
- - ```css - .parent-element { - text-align: center; - } - - .inherited-text { - text-align: inherit; - } - ``` - -
- - -
-

This text inherits the alignment from the parent.

-
-
- -:::tip Extra Tip - -The `text-align` property can be combined with other CSS properties to create complex text layouts and designs. Experiment with different combinations to achieve the desired visual effects. - -::: - -## Conclusion - -The `text-align` property in CSS is a powerful tool for aligning text elements within a container. By using this property with different values, you can control the horizontal alignment of text on your web page, creating visually appealing layouts that enhance the readability and aesthetics of your content. Experiment with the `text-align` property to achieve the desired text alignment for your web projects. \ No newline at end of file diff --git a/docs/css/fonts-and-text-properties/font-size.md b/docs/css/fonts-and-text-properties/font-size.md deleted file mode 100644 index 385375f7d..000000000 --- a/docs/css/fonts-and-text-properties/font-size.md +++ /dev/null @@ -1,354 +0,0 @@ ---- -id: font-size -title: "CSS Font Size" -sidebar_label: "Font Size" -sidebar_position: 2 -keywords: - - css font size - - font size css - - css text size - - css font size property - - css font size example -description: Learn how to set the font size of text using the CSS font-size property. -tags: - - css - - font size - - css font size - - css text size - - css font size property - - css font size example ---- - -In CSS, the `font-size` property is used to set the size of text content. You can specify the font size in various units such as pixels, ems, rems, percentages, and more. By adjusting the font size, you can control the visual appearance of text on your web page, making it larger or smaller as needed. - - - -## Syntax - -The `font-size` property in CSS has the following syntax: - -```css title="index.css" -selector { - font-size: value; -} -``` - -- `selector`: The CSS selector that targets the text content you want to apply the font size to. -- `value`: The size of the text content. This can be specified in various units such as pixels (`px`), ems (`em`), rems (`rem`), percentages (`%`), and more. -- The `font-size` property can be applied to any HTML element that contains text content, such as headings, paragraphs, and spans. -- The `font-size` property affects the size of the text content but does not change the size of the element itself. It only adjusts the appearance of the text within the element. - - - -:::info Note -The default font size for most browsers is `16px`. If you do not specify a font size for text content, it will be displayed at the browser's default size. -::: - -## Examples - -### 1. Setting the Font Size in Pixels - -You can set the font size of text content using pixels (`px`) as the unit of measurement. In the following example, we set the font size of a paragraph to `16px`: - - - - ```html - - - - - - Font Size Example - - - -

This is a paragraph with a font size of 16px.

- - - ``` -
- - ```css - .text { - font-size: 16px; - } - ``` - -
- - -

This is a paragraph with a font size of 16px.

-
- -### 2. Setting the Font Size in Em Units - -You can also set the font size using ems (`em`) as the unit of measurement. The `em` unit is relative to the font size of the parent element. In the following example, we set the font size of a paragraph to `1.5em`, which is 1.5 times the font size of its parent element: - - - - ```html - - - - - - Font Size Example - - - -
-

This is a paragraph with a font size of 1.5em.

-
- - - ``` -
- - ```css - .parent { - font-size: 20px; - } - - .text { - font-size: 1.5em; - } - ``` - -
- - -
-

This is a paragraph with a font size of 1.5em.

-
-
- - - -:::info Note -When using em units, the font size of an element is calculated relative to the font size of its parent element. If the parent element does not have a specified font size, the browser's default font size (`16px`) is used as the reference. -::: - -### 3. Setting the Font Size in Percentages - -You can specify the font size using percentages (`%`) as a relative unit of measurement. In the following example, we set the font size of a paragraph to `150%`, which is 1.5 times the default font size: - - - - ```html - - - - - - Font Size Example - - - -

This is a paragraph with a font size of 150%.

- - - ``` -
- - ```css - .text { - font-size: 150%; - } - ``` - -
- - -

This is a paragraph with a font size of 150%.

-
- -### 4. Setting the Font Size Using Rem Units - -You can also use rems (`rem`) as a relative unit of measurement for font size. The `rem` unit is relative to the font size of the root element (``). In the following example, we set the font size of a paragraph to `1.5rem`, which is 1.5 times the font size of the root element: - - - - ```html - - - - - - Font Size Example - - - -

This is a paragraph with a font size of 1.5rem.

- - - ``` -
- - ```css - .text { - font-size: 1.5rem; - } - ``` - -
- - -

This is a paragraph with a font size of 1.5rem.

-
- - - -:::info Note -When using rem units, the font size of an element is calculated relative to the font size of the root element (``). This makes it easier to maintain consistent font sizes across your web page. -::: - -### 5. Setting the Font Size Using Keywords - -You can also use keywords to specify the font size. Common keywords include `small`, `medium`, `large`, and `x-large`. In the following example, we set the font size of a paragraph to `large`: - - - - ```html - - - - - - Font Size Example - - - -

This is a paragraph with a font size of large.

- - - ``` -
- - ```css - .text { - font-size: large; - } - ``` - -
- - -

This is a paragraph with a font size of large.

-
- -### 6. Setting the Font Size Using Viewport Units - -You can also use viewport units (`vw`, `vh`, `vmin`, `vmax`) to specify the font size relative to the size of the viewport. In the following example, we set the font size of a paragraph to `5vw`, which is 5% of the viewport width: - - - - ```html - - - - - - Font Size Example - - - -

This is a paragraph with a font size of 5vw.

- - - ``` -
- - ```css - .text { - font-size: 5vw; - } - ``` - - -
- - -

This is a paragraph with a font size of 5vw.

-
- -:::info Note -Viewport units (`vw`, `vh`, `vmin`, `vmax`) are relative to the size of the viewport. Using viewport units allows you to create responsive designs where text scales based on the size of the viewport. -::: - - - -### 7. Setting the Font Size Using Absolute Units - -You can also use absolute units such as `in` (inches), `cm` (centimeters), `mm` (millimeters), `pt` (points), and `pc` (picas) to specify the font size. In the following example, we set the font size of a paragraph to `12pt`: - - - - ```html - - - - - - Font Size Example - - - -

This is a paragraph with a font size of 12pt.

- - - ``` -
- - ```css - .text { - font-size: 12pt; - } - ``` - -
- - -

This is a paragraph with a font size of 12pt.

-
- -### 8. Setting the Font Size Using Custom Units - -You can define custom units for font size using CSS variables. In the following example, we define a custom unit called `--custom-size` and set the font size of a paragraph using this custom unit: - - - - ```html - - - - - - Font Size Example - - - -

This is a paragraph with a custom font size.

- - - ``` -
- - ```css - :root { - --custom-size: 24px; - } - - .text { - font-size: var(--custom-size); - } - ``` - -
- - -

This is a paragraph with a custom font size.

-
- -## Conclusion - -The `font-size` property in CSS allows you to control the size of text content on your web page. By specifying the font size using different units of measurement, you can adjust the appearance of text to suit your design requirements. Experiment with different font sizes to find the right balance between readability and aesthetics for your web content. \ No newline at end of file diff --git a/docs/css/fonts-and-text-properties/font-style.md b/docs/css/fonts-and-text-properties/font-style.md deleted file mode 100644 index 487233944..000000000 --- a/docs/css/fonts-and-text-properties/font-style.md +++ /dev/null @@ -1,152 +0,0 @@ ---- -id: font-style -title: "CSS Font Style" -sidebar_label: "Font Style" -sidebar_position: 7 -keywords: - - css font style - - css font style property - - css font style values - - css font style examples - - css text properties -description: Learn how to use the CSS `font-style` property to style the italic or oblique text on your web page. -tags: - - css - - font style - - css font style - - css font style property - - css font style values - - css text properties ---- - -In CSS, the `font-style` property is used to specify the style of a font, such as italic or oblique. It allows you to apply different text styles to your web page, making text elements appear italicized or slanted as needed. The `font-style` property accepts several values that control the appearance of text, providing you with flexibility in styling your content. - - - -## Syntax - -The `font-style` property in CSS has the following syntax: - -```css title="index.css" -selector { - font-style: normal | italic | oblique; -} -``` - -The `font-style` property can be applied to any text element on your web page using the appropriate selector. It accepts the following values: - -- `normal`: The default value. The text is displayed in a standard, upright style. -- `italic`: The text is displayed in an italic style, which is typically a slanted version of the normal font. -- `oblique`: The text is displayed in an oblique style, which is similar to italic but less common. -- `initial`: Sets the property to its default value. -- `inherit`: Inherits the property from its parent element. - -## Example - -Let's look at an example to see how the `font-style` property works in CSS: - - - - ```html - - - - - - Font Style Example - - - -

Italic Text

-

Oblique Text

-

Normal Text

- - - ``` - -
- - ```css - .italic { - font-style: italic; - } - - .oblique { - font-style: oblique; - } - - .normal { - font-style: normal; - } - ``` - -
- - - <> -

Italic Text

-

Oblique Text

-

Normal Text

- -
- -:::note try it yourself - -Experiment with different font styles to see how they affect the appearance of text elements on your web page. - -::: - - - -## Inheriting Font Style - -When you apply the `font-style` property to a parent element, its value is inherited by its child elements. This means that if you set the `font-style` property on a container element, such as a `div` or `section`, all text elements inside that container will inherit the specified font style. - -Here's an example that demonstrates how font style inheritance works in CSS: - - - - ```html - - - - - - Inherited Font Style - - - -
-

This text inherits the font style from the parent.

-
- - - ``` - -
- - ```css - .parent-element { - font-style: italic; - } - ``` - -
- - - <> -
-

This text inherits the font style from the parent.

-
- -
- -:::note try it yourself - -Try changing the font style value on the parent element to see how it affects the child elements that inherit the font style. - -::: - -## Conclusion - -The `font-style` property in CSS allows you to control the style of text elements on your web page, making them appear italicized or oblique as needed. By using the `font-style` property with different values, you can customize the appearance of text to suit your design requirements. Additionally, font style inheritance provides a convenient way to apply consistent styling to text elements within a container. \ No newline at end of file diff --git a/docs/css/fonts-and-text-properties/font-weight.md b/docs/css/fonts-and-text-properties/font-weight.md deleted file mode 100644 index ce3a6c103..000000000 --- a/docs/css/fonts-and-text-properties/font-weight.md +++ /dev/null @@ -1,208 +0,0 @@ ---- -id: font-weight -title: "CSS Font Weight" -sidebar_label: "Font Weight" -sidebar_position: 3 -keywords: - - css font weight - - font weight css - - css bold text - - css font weight property - - css font weight values -description: Learn how to use the CSS `font-weight` property to control the thickness of text in your web page. -tags: - - css - - font weight - - css font weight - - css bold text - - css font weight property - - css font weight values ---- - -In CSS, the `font-weight` property is used to specify the thickness or boldness of a font. It allows you to control the visual weight of text elements on your web page, making them appear lighter or bolder as needed. The `font-weight` property accepts a variety of values that range from `100` (thin) to `900` (bold), providing you with fine-grained control over the appearance of text. - - - -## Syntax - -The `font-weight` property in CSS has the following syntax: - -```css title="index.css" -selector { - font-weight: value; -} -``` - -- `selector`: The CSS selector that targets the text element you want to apply the font weight to. -- `value`: A numeric or keyword value that represents the thickness of the font. The `font-weight` property accepts the following values: - - `normal`: Sets the font weight to the normal level (equivalent to `400`). - - `bold`: Sets the font weight to a bold level (equivalent to `700`). - - `bolder`: Increases the font weight relative to the parent element. - - `lighter`: Decreases the font weight relative to the parent element. - - `100` to `900`: Numeric values that represent the font weight, with `100` being the thinnest and `900` being the boldest. - -## Examples - -### 1. Setting the Font Weight to Bold - -You can use the `font-weight` property to make text elements appear bold by setting the value to `bold`. In the following example, we make a paragraph element bold: - - - - ```html - - - - - - Bold Text - - - -

This text is bold.

- - - ``` -
- - ```css - .bold-text { - font-weight: bold; - } - ``` - -
- - -

This text is bold.

-
- -:::info Informaton - -The `font-weight` property can be applied to various text elements, such as headings, paragraphs, and spans, to create different visual styles. - -::: - - - -### 2. Using Numeric Values for Font Weight - -You can specify the font weight using numeric values ranging from `100` to `900`. In the following example, we set the font weight of a heading element to `700` (bold): - - - - ```html - - - - - - Bold Heading - - - -

This is a bold heading.

- - - ``` -
- - ```css - .bold-heading { - font-weight: 700; - } - ``` - -
- - -

This is a bold heading.

-
- -### 3. Adjusting Font Weight Relative to Parent Element - -You can use the `bolder` and `lighter` values to adjust the font weight relative to the parent element. In the following example, we make a paragraph element lighter than its parent: - - - - ```html - - - - - - Lighter Text - - - -
-

This text is lighter than the parent.

-
- - - ``` -
- - ```css - .parent-element { - font-weight: bold; - } - - .lighter-text { - font-weight: lighter; - } - ``` - -
- - -
-

This text is lighter than the parent.

-
-
- -:::info Note - -The `bolder` and `lighter` values adjust the font weight relative to the parent element's font weight. If the parent element has a font weight of `normal`, the `bolder` value will make the text bold, while the `lighter` value will make it lighter. - -::: - -### 4. Using `font-weight` with Other Properties - -You can combine the `font-weight` property with other text properties to create custom text styles. In the following example, we set the font weight, font size, and font family of a paragraph element: - - - - ```html - - - - - - Custom Text Style - - - -

This is custom text.

- - - ``` -
- - ```css - .custom-text { - font-weight: bold; - font-size: 1.2em; - font-family: Arial, sans-serif; - } - ``` - -
- - -

This is custom text.

-
- -## Conclusion - -The `font-weight` property in CSS allows you to control the thickness of text elements on your web page, making them appear lighter or bolder as needed. By using the `font-weight` property with different values, you can create visually appealing text styles that enhance the readability and aesthetics of your content. Experiment with the `font-weight` property to find the right balance of boldness for your text elements. \ No newline at end of file diff --git a/docs/css/fonts-and-text-properties/generic-vs-specific-font-families.md b/docs/css/fonts-and-text-properties/generic-vs-specific-font-families.md deleted file mode 100644 index 7d7521a58..000000000 --- a/docs/css/fonts-and-text-properties/generic-vs-specific-font-families.md +++ /dev/null @@ -1,88 +0,0 @@ ---- -id: generic-vs-specific-font-families -title: "CSS Generic vs. Specific Font Families" -sidebar_label: "Generic vs. Specific Font Families" -sidebar_position: 1 -keywords: - - css font families - - css generic font families - - css specific font families - - css font-family property - - css font-family values -description: Learn the difference between generic and specific font families in CSS and how to use them to style text on your web page. -tags: - - css - - font families - - css font families - - css generic font families - - css specific font families - - css font-family property - - css font-family values ---- - -In CSS, font families are used to define the typeface or font style that should be applied to text elements on a web page. There are two types of font families you can use in CSS: generic font families and specific font families. Understanding the difference between these two types of font families is essential for styling text effectively and ensuring consistent typography across your website. - - - -## Generic Font Families - -Generic font families are broad categories of fonts that share similar characteristics and styles. They provide a general description of the type of font to be used, allowing the browser to choose an appropriate font based on the category specified. Generic font families are useful when you want to define a fallback font that can be used if a specific font is not available on the user's system. - -The following are the five generic font families defined in CSS: - -1. `serif`: Fonts that have decorative strokes at the ends of characters. Examples include Times New Roman, Georgia, and Palatino. -2. `sans-serif`: Fonts that do not have decorative strokes at the ends of characters. Examples include Arial, Helvetica, and Verdana. -3. `monospace`: Fonts where each character occupies the same amount of horizontal space. Examples include Courier New, Consolas, and Monaco. -4. `cursive`: Fonts that mimic handwriting styles. Examples include Comic Sans MS and Brush Script. -5. `fantasy`: Fonts that are decorative and often unconventional. Examples include Impact and Papyrus. - -When using generic font families in CSS, you can specify multiple font families as fallback options in case the user's system does not have the primary font installed. For example, you can define a font stack that includes a specific font family followed by a generic font family as a fallback: - -```css title="index.css" -selector { - font-family: 'Open Sans', sans-serif; -} -``` - -In this example, the font stack specifies 'Open Sans' as the primary font family and `sans-serif` as the fallback font family. If 'Open Sans' is not available, the browser will use a sans-serif font instead. - -## Specific Font Families - -Specific font families, also known as named font families, refer to fonts that are identified by their unique names or font families. These fonts are typically custom or web fonts that are loaded from external sources or included in the web page using `@font-face` rules. Specific font families allow you to use custom fonts that are not available on the user's system, ensuring consistent typography across different devices and browsers. - -To use a specific font family in CSS, you need to define the font family name or font stack that includes the specific font family as follows: - -```css title="index.css" -@font-face { - font-family: 'MyCustomFont'; - src: url('mycustomfont.woff2') format('woff2'); -} - -selector { - font-family: 'MyCustomFont', sans-serif; -} -``` - -In this example, we define a specific font family named 'MyCustomFont' using the `@font-face` rule and specify the source of the font file. We then apply the 'MyCustomFont' font family to a selector, with `sans-serif` as the fallback font family. - -Specific font families give you the flexibility to use unique fonts in your web designs, enhancing the visual appeal of your text elements and creating a distinctive typographic style for your website. - -By understanding the difference between generic and specific font families in CSS, you can effectively style text elements on your web page and choose the appropriate font families to achieve the desired typographic effects. Whether you need a fallback font for broader compatibility or a custom font for a unique design, CSS font families provide you with the tools to create visually appealing and consistent typography for your website. - -## Differences Between Generic and Specific Font Families - -The key differences between generic and specific font families in CSS are as follows: - -|No. | Feature | Generic Font Families | Specific Font Families | -|----|-------------------------|-----------------------|------------------------| -|1. | Definition | Broad categories of fonts with similar characteristics. | Unique fonts identified by their names or font families. | -|2. | Usage | Used as fallback options when specific fonts are not available. | Used to apply custom or web fonts to text elements. | -|3. | Examples | `serif`, `sans-serif`, `monospace`, `cursive`, `fantasy`. | `MyCustomFont`, `Open Sans`, `Roboto`, etc. | -|4. | Availability | Widely available on most systems and browsers. | Requires loading custom fonts from external sources. | -|5. | Compatibility | Ensures consistent text rendering across different devices. | Enhances visual appeal and design uniqueness. | - -Understanding these differences will help you make informed decisions when choosing font families for your web projects and ensure that your text elements are displayed correctly and consistently across various platforms. - -## Conclusion - -Font families play a crucial role in defining the visual appearance of text on a web page. By using generic font families as fallback options and specific font families for custom fonts, you can ensure that your text elements are displayed consistently across different devices and browsers. Experiment with different font families to find the right combination that suits your design requirements and enhances the readability and aesthetics of your content. \ No newline at end of file diff --git a/docs/css/introduction/_category_.json b/docs/css/introduction/_category_.json deleted file mode 100644 index b490ad00f..000000000 --- a/docs/css/introduction/_category_.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "label": "Introduction", - "position": 1, - "link": { - "type": "generated-index", - "description": "In this section, you will learn about the CSS. CSS stands for Cascading Style Sheets. It is a style sheet language used for describing the presentation of a document written in a markup language like HTML. CSS is a cornerstone technology of the World Wide Web, alongside HTML and JavaScript." - } - } \ No newline at end of file diff --git a/docs/css/introduction/comments-in-css.md b/docs/css/introduction/comments-in-css.md deleted file mode 100644 index 4be6437a8..000000000 --- a/docs/css/introduction/comments-in-css.md +++ /dev/null @@ -1,130 +0,0 @@ ---- -id: comments-in-css -title: Comments in CSS -sidebar_label: Comments in CSS -sidebar_position: 3 -tags: - [ - comments-in-css, - css-introduction, - css, - introduction, - css-basics, - css-tutorial, - css-guide, - css-tutorial-for-beginners, - learn-css, - css-tutorial-for-beginners, - css-tutorial-for-beginners-2025, - css-tutorial-for-learning, - ] -description: In this tutorial, you will learn how to add comments to your CSS code to make it more readable and maintainable. -keywords: - [ - comments in css, - css comments, - css introduction, - css basics, - css tutorial, - css guide, - css tutorial for beginners, - learn css, - css tutorial for beginners 2025, - css tutorial for learning, - ] ---- - -In this tutorial, you will learn how to add comments to your CSS code to make it more readable and maintainable. Comments are used to explain the purpose of the code, provide context, and make it easier for other developers (or your future self) to understand and modify the code. - - - -## Comments in CSS - -Comments in CSS are similar to comments in other programming languages. They are used to add notes and explanations to your code without affecting the output. Comments can be single-line or multi-line and are ignored by the browser when rendering the page. - -### Single-line Comments - -Single-line comments start with `//` and continue until the end of the line. They are useful for adding short notes or explanations to your code. Here's an example of a single-line comment in CSS: - -```css title="styles.css" showLineNumbers -/* This is a single-line comment */ -``` - -### Multi-line Comments - -Multi-line comments start with `/*` and end with `*/`. They can span multiple lines and are useful for adding longer notes or explanations to your code. Here's an example of a multi-line comment in CSS: - -```css title="styles.css" showLineNumbers -/* -This is a multi-line comment -that spans multiple lines -*/ -``` - -### Why Use Comments in CSS - -Comments are an essential part of writing clean and maintainable code. Here are some reasons why you should use comments in your CSS code: - -- **Explain the Purpose**: Comments help explain the purpose of the code, making it easier for other developers to understand. -- **Provide Context**: Comments provide context and background information about the code, helping developers make informed decisions. -- **Document Changes**: Comments document changes made to the code, making it easier to track modifications and updates. -- **Improve Readability**: Comments improve the readability of the code by breaking it down into logical sections and adding explanations. -- **Debugging**: Comments can be used to temporarily disable or troubleshoot code without deleting it. -- **Future Reference**: Comments serve as a reference for future modifications or updates to the code. -- **Collaboration**: Comments facilitate collaboration among team members by explaining the code and its purpose. -- **Best Practices**: Using comments is considered a best practice in programming and helps maintain code quality. -- **Code Documentation**: Comments can be used to generate documentation for the codebase, making it easier to understand and maintain. -- **Learning**: Comments help beginners learn CSS by providing explanations and examples. -- **Code Review**: Comments can be used during code reviews to explain the code and suggest improvements. -- **Maintainability**: Comments improve the maintainability of the code by providing insights into its structure and logic. - -By adding comments to your CSS code, you can make it more readable, maintainable, and understandable for yourself and other developers. Comments are a powerful tool for documenting your code and ensuring its quality and longevity. - - - -## For example - - - - ```html showLineNumbers - - - - Comments in CSS Example - - - -

Welcome to CSS Comments

-

This is an example of how comments can be used in CSS.

- - - ``` -
- - ```css showLineNumbers - /* This is a CSS comment */ - h1 { - color: navy; /* Set the color of the heading */ - } - ``` - -
- -Now, let's see how the above example looks in a browser window: - - - <> -

Welcome to CSS Comments

-

This is an example of how comments can be used in CSS.

- -
- -In this example, we have added comments to the CSS code to explain the purpose of the styles and provide context for the code. The comments help clarify the intent of the code and make it easier to understand and maintain. - -By using comments in your CSS code, you can enhance the quality, readability, and maintainability of your stylesheets. Comments are a valuable tool for documenting your code and ensuring that it remains clear and understandable over time. - -Now that you have learned how to add comments to your CSS code, you can start using comments to document your stylesheets and make them more accessible and maintainable. Comments are an essential part of writing clean and professional CSS code, and they play a crucial role in improving the quality and readability of your stylesheets. - -## Conclusion - -In this tutorial, you learned how to add comments to your CSS code to make it more readable and maintainable. Comments are an essential part of writing clean and professional CSS code, and they help explain the purpose of the code, provide context, and improve readability. By using comments in your CSS stylesheets, you can enhance the quality and maintainability of your code and make it easier for other developers to understand and modify. \ No newline at end of file diff --git a/docs/css/introduction/how-to-add-css-to-html.md b/docs/css/introduction/how-to-add-css-to-html.md deleted file mode 100644 index 5b239b7c0..000000000 --- a/docs/css/introduction/how-to-add-css-to-html.md +++ /dev/null @@ -1,180 +0,0 @@ ---- -id: how-to-add-css-to-html -title: How to Add CSS to HTML -sidebar_label: How to Add CSS to HTML -sidebar_position: 2 -tags: - [ - how-to-add-css-to-html, - css-introduction, - css, - introduction, - css-basics, - css-tutorial, - css-guide, - css-tutorial-for-beginners, - learn-css, - css-tutorial-for-beginners, - css-tutorial-for-beginners-2025, - css-tutorial-for-learning, - ] -description: In this tutorial, you will learn how to add CSS to an HTML document using internal, external, and inline styles. -keywords: - [ - how to add css to html, - add css to html, - css introduction, - css basics, - css tutorial, - css guide, - css tutorial for beginners, - learn css, - css tutorial for beginners 2025, - css tutorial for learning, - ] ---- - -In this tutorial, you will learn how to add CSS to an HTML document using internal, external, and inline styles. CSS (Cascading Style Sheets) is a style sheet language that is used to describe the look and formatting of a document written in HTML or XML. It allows you to style web pages and user interfaces, making it easier to create visually appealing and responsive websites. - - - -## How to Add CSS to HTML - -There are three ways to add CSS to an HTML document: - -### 1. Internal CSS - -Internal CSS is added within the ` - - -

Welcome to My Website -

This is an example of internal CSS.

- - -``` - -In this example, the background color of the `` element is set to `lightblue`, and the color and alignment of the `

` element are defined using internal CSS. - -When you run this HTML document in a web browser. It will display the content with the styles defined in the internal CSS. - - - <> -

Welcome to My Website

-

This is an example of internal CSS.

- -
- - - -### 2. External CSS - -External CSS is added in a separate CSS file and linked to an HTML document using the `` element in the `` section. It allows you to define styles that can be shared across multiple documents. Here's an example of how to add external CSS to an HTML document: - -```html title="index.html" - - - - External CSS Example - - - -

Welcome to My Website -

This is an example of external CSS.

- - -``` - -And create a separate CSS file named `styles.css` with the following content: - -```css title="styles.css" -body { - background-color: lightblue; -} - -h1 { - color: navy; - text-align: center; -} -``` - -In this example, the CSS styles are defined in a separate file named `styles.css`, which is linked to the HTML document using the `` element. The styles defined in the external CSS file are applied to the elements in the HTML document. - - - -When you run this HTML document in a web browser. It will display the content with the styles defined in the external CSS. - - - <> -

Welcome to My Website

-

This is an example of external CSS.

- -
- -### 3. Inline CSS - -Inline CSS is added directly to an HTML element using the `style` attribute. It allows you to define styles that apply only to that specific element. Here's an example of how to add inline CSS to an HTML document: - -```html title="index.html" - - - - Inline CSS Example - - -

Welcome to My Website

-

This is an example of inline CSS.

- - -``` - -In this example, the color and alignment of the `

` element and the color of the `

` element are defined using inline CSS. - -When you run this HTML document in a web browser. It will display the content with the styles defined in the inline CSS. - - - <> -

Welcome to My Website

-

This is an example of inline CSS.

- - - -By using internal, external, and inline CSS, you can style web pages and user interfaces to create visually appealing and responsive websites. - - - -:::note -1. Make sure the `styles.css` file is in the same directory as the `index.html` file. -2. The `` element should be placed in the `` section of the HTML document. -3. The `href` attribute of the `` element should point to the location of the external CSS file. -4. `` where: - - `rel="stylesheet"` specifies the relationship between the HTML document and the linked CSS file. - - `href="styles.css"` specifies the location of the external CSS file. -5. The `style` attribute is used to add inline CSS to an HTML element. -6. The `style` attribute contains one or more CSS property-value pairs separated by a semicolon. -7. The CSS property is followed by a colon (`:`) and the property value. -8. The CSS property-value pairs are enclosed in double quotes (`"`). -9. The CSS property-value pairs are separated by a semicolon (`;`). -10. The `style` attribute is added directly to the HTML element. -11. The `style` attribute overrides any styles applied to the element using internal or external CSS. -12. The `style` attribute is not recommended for large-scale styling as it can make the HTML document harder to maintain. -::: - -## Conclusion - -In this tutorial, you learned how to add CSS to an HTML document using internal, external, and inline styles. Internal CSS is added within the ` -

- Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed do eiusmod - tempor incididunt ut labore et dolore magna aliqua. -

-

- - -In the above example, the CSS rule will apply the `font-weight: bold` and `font-size: 1.2em` properties to the first line of text inside the `

` element. - - - -## Summary - -Pseudo-elements selectors are used to style parts of an element that are not part of the document tree. Pseudo-elements selectors are represented by double colons `::` followed by the name of the pseudo-element. Pseudo-elements selectors allow you to style specific parts of an element, such as the first letter or line of a block of text, without adding extra markup to the HTML document. Pseudo-elements selectors are useful for adding decorative elements to text or styling specific parts of an element. Pseudo-elements selectors can be combined with other selectors to create complex styles. Pseudo-elements selectors are supported in all modern browsers. Pseudo-elements selectors are used to style parts of an element that are not part of the document tree. Pseudo-elements selectors are used to style specific parts of an element, such as the first letter or line of a block of text. \ No newline at end of file diff --git a/docs/css/selectors/simple-selectors/_category_.json b/docs/css/selectors/simple-selectors/_category_.json deleted file mode 100644 index ecebf791d..000000000 --- a/docs/css/selectors/simple-selectors/_category_.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "label": "Simple Selectors", - "position": 1, - "link": { - "type": "generated-index", - "description": "In this section, you will learn about the simple selectors in CSS. Simple selectors are the most basic type of selectors. They are used to select elements based on their type, class, id, or attribute. Simple selectors are the building blocks of more complex selectors." - } - } \ No newline at end of file diff --git a/docs/css/selectors/simple-selectors/class-selector.md b/docs/css/selectors/simple-selectors/class-selector.md deleted file mode 100644 index 8ec3cdf9e..000000000 --- a/docs/css/selectors/simple-selectors/class-selector.md +++ /dev/null @@ -1,448 +0,0 @@ ---- -id: class-selector -title: Class Selector -sidebar_label: Class Selector -sidebar_position: 2 -tags: - [ - class-selector, - css-selectors, - css, - selectors, - simple-selectors, - css-basics, - css-tutorial, - css-guide, - css-tutorial-for-beginners, - learn-css, - css-tutorial-for-beginners-2025, - css-tutorial-for-learning, - ] -description: The class selector is used to select elements on a web page based on their class attribute. -keywords: - [ - class selector, - css class selector, - css selectors, - css basics, - css tutorial, - css guide, - css tutorial for beginners, - learn css, - css tutorial for beginners 2025, - css tutorial for learning, - ] ---- - -In CSS, the class selector is used to select elements on a web page based on their class attribute. It is denoted by a dot (`.`) followed by the class name. - - - -## What is a Class Selector? - -A class selector selects all elements on a web page that have a specified class attribute. It targets HTML elements based on the value of their `class` attribute. For example, to select all elements with the class `highlight`, you would use the following CSS rule: - -```css title="styles.css" -.highlight { - background-color: yellow; -} -``` - -In this example, the CSS rule selects all elements with the class `highlight` and sets their background color to yellow. The class selector is denoted by a dot (`.`) followed by the class name (`highlight` in this case) and curly braces `{}` containing the CSS properties and values to apply to the selected elements. - -## Syntax of the Class Selector - -The syntax of the class selector is - -```css title="styles.css" -.classname { - property: value; -} -``` - -where `.classname` represents the class selector, and `property: value;` represents the CSS properties and values to apply to the selected elements. - -:::tip Key Points to Remember -1. **Reusability:** Classes are reusable and can be applied to multiple elements across your HTML document. -2. **Combining Classes:** You can assign multiple classes to a single HTML element by separating class names with spaces. -3. **Higher Specificity:** Class selectors are more specific than element selectors but less specific than ID selectors. -::: - -By using class selectors, you can style specific groups of elements based on their class attributes, making it a powerful tool for styling web pages. - -## Example - - - - ```html showLineNumbers - - - - - - CSS Class Selector - - - -

Welcome to the CSS Tutorial!

-

This paragraph has a highlighted style.

-

This paragraph is both highlighted and bold.

-
-

Card Title

-

This is some content inside a card.

-
- - - - - ``` - - - ```css showLineNumbers - /* Basic styling for the title */ - .title { - font-size: 2rem; - color: #2c3e50; - text-align: center; - } - - /* Highlighted text styling */ - .highlight { - background-color: #f9f871; - color: #333; - padding: 5px; - border-radius: 5px; - } - - /* Add bold text styling */ - .bold { - font-weight: bold; - } - - /* Card styles */ - .card { - border: 1px solid #ccc; - border-radius: 10px; - padding: 20px; - margin: 20px 0; - box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1); - } - - .card-title { - font-size: 1.5rem; - color: #007bff; - } - - .card-content { - font-size: 1rem; - color: #555; - } - - /* Button styling */ - .btn { - background-color: #2ecc71; - color: white; - border: none; - padding: 10px 15px; - font-size: 14px; - border-radius: 5px; - cursor: pointer; - } - - /* Additional styling for primary buttons */ - .btn-primary { - background-color: #3498db; - } - - .btn:hover { - opacity: 0.8; - } - ``` - - - -Now, you can see the output of the above code in the Browser Window like this: - - - <> -

Welcome to the CSS Tutorial!

-

This paragraph has a highlighted style.

-

This paragraph is both highlighted and bold.

-
-

Card Title

-

This is some content inside a card.

-
-   - - -
- -In the above example, we have used the class selector to style different elements on the web page based on their class attributes. The `highlight` class is used to style paragraphs with a highlighted background color, the `bold` class is used to make text bold, and the `card` class is used to style a card-like container. The `btn` class is used to style buttons, and the `btn-primary` class is used to style primary buttons differently. - - - -By using class selectors, you can apply consistent styles to elements with the same class across your web page, making it easier to maintain and update the styles. - -## Multiple Classes - -You can assign multiple classes to a single HTML element by separating class names with spaces. This allows you to combine styles from different classes on the same element. For example: - -```html title="index.html" - -``` - -In this example, the button element has both the `btn` and `btn-primary` classes applied to it. This allows you to style the button using styles from both classes. - -## Tips & Tricks for Using Class Selectors - -1. **Use Descriptive Names:** Choose meaningful class names to make your code more readable and maintainable. For example, use `btn-primary` instead of `blue-button`. - - For example: - -
- ```css title="Bad Example" showLineNumbers - .blue-button { - background-color: blue; - color: white; - padding: 10px 20px; - border-radius: 5px; - } - ``` - - ```css title="Good Example" showLineNumbers - .btn-primary { - background-color: blue; - color: white; - padding: 10px 20px; - border-radius: 5px; - } - ``` -
- -2. **Avoid Inline Styles:** Instead of using inline styles, apply styles using class selectors to keep your CSS separate from your HTML. - - For example: - - ```html title="Bad Example" showLineNumbers - - ``` - - ```html title="Good Example" showLineNumbers - - ``` - -3. **Avoid Over-Nesting:** Try to keep your class selectors flat and avoid deep nesting to maintain a clear and concise style structure. - - For example: - - ```css title="Bad Example" showLineNumbers - .card .content .title { - font-size: 1.5rem; - color: #333; - } - ``` - - ```css title="Good Example" showLineNumbers - .card-title { - font-size: 1.5rem; - color: #333; - } - ``` - -4. **Combine Classes:** Use multiple classes on an element to combine styles and create reusable components. - - For example: - - ```html title="index.html" showLineNumbers - - ``` - - ```css title="styles.css" showLineNumbers - .btn { - padding: 10px 20px; - border-radius: 5px; - } - - .btn-primary { - background-color: blue; - color: white; - } - ``` - -5. **Utility Classes:** Consider using utility classes for common styles like margins, padding, and text alignment to keep your CSS concise and modular. - - For example: - - ```html title="index.html" showLineNumbers -
-

Centered Text

-
- ``` - - ```css title="styles.css" showLineNumbers - .flex { - display: flex; - } - - .justify-center { - justify-content: center; - } - - .items-center { - align-items: center; - } - - .p-4 { - padding: 1rem; - } - - .text-center { - text-align: center; - } - ``` - -6. **CSS Framework-Like Approach:** Adopt a framework-like approach with predefined class structures for buttons, grids, cards, etc. - - For example: - - ```html title="index.html" showLineNumbers -
-

Card Title

-

This is some content inside a card.

-
- ``` - - ```css title="styles.css" showLineNumbers - .card { - border: 1px solid #ccc; - border-radius: 10px; - padding: 20px; - margin: 20px 0; - box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1); - } - - .card-title { - font-size: 1.5rem; - color: #007bff; - } - - .card-content { - font-size: 1rem; - color: #555; - } - ``` - -7. **Debugging Tip:** Use browser developer tools to inspect elements and check which styles are being applied to them. This can help you troubleshoot styling issues and conflicts. - -By following these tips and best practices, you can effectively use class selectors to style your web pages and create maintainable CSS code. - - - -## Advanced Usage of Class Selectors - -### Combining Class Selectors - -You can combine multiple class selectors to create more specific styles for elements that have both classes applied. For example: - -```css title="styles.css" -.btn { - padding: 10px 20px; - border-radius: 5px; -} - -.btn-primary { - background-color: blue; - color: white; -} - -.btn.btn-primary { - font-weight: bold; -} -``` - -In this example, the `.btn.btn-primary` selector targets elements that have both the `btn` and `btn-primary` classes applied to them. This allows you to create more specific styles for elements with multiple classes. - -### Pseudo-Classes with Class Selectors - -You can also use pseudo-classes in combination with class selectors to style elements based on their state or interaction. For example: - -```css title="styles.css" -.btn { - padding: 10px 20px; - border-radius: 5px; -} - -.btn:hover { - background-color: #3498db; - color: white; -} -``` - -In this example, the `.btn:hover` selector applies styles to the button when it is hovered over by the user. Pseudo-classes can be a powerful way to add interactivity to your web page using class selectors. - - - -### Nesting Class Selectors - -While CSS does not support true nesting of selectors, you can simulate nesting by chaining class selectors together. For example: - -```css title="styles.css" -.card { - border: 1px solid #ccc; - border-radius: 10px; - padding: 20px; - margin: 20px 0; - box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1); -} - -.card .card-title { - font-size: 1.5rem; - color: #007bff; -} - -.card .card-content { - font-size: 1rem; - color: #555; -} -``` - -In this example, the `.card .card-title` and `.card .card-content` selectors simulate nesting by targeting elements with the `card-title` and `card-content` classes that are descendants of elements with the `card` class. - -### Attribute Selectors with Class Selectors - -You can also use attribute selectors in combination with class selectors to target elements based on their attributes. For example: - -```css title="styles.css" -.btn { - padding: 10px 20px; - border-radius: 5px; -} - -.btn[type="submit"] { - background-color: #2ecc71; - color: white; -} - -.btn[type="reset"] { - background-color: #e74c3c; - color: white; -} -``` - -In this example, the `.btn[type="submit"]` and `.btn[type="reset"]` selectors target buttons with the `btn` class and specific `type` attributes, applying different styles based on the button type. - - - -By using these advanced techniques, you can create more complex and specific styles for your web page using class selectors. - -## When to Use Class Selectors - -Class selectors are ideal for styling groups of elements that share common styles or characteristics. Here are some scenarios where class selectors are commonly used: - -1. **Reusable Styles:** Use class selectors to create reusable styles that can be applied to multiple elements across your web page. -2. **Component Styling:** Apply class selectors to style components or sections of your web page consistently. -3. **Button Styling:** Use class selectors to style buttons with different variations (e.g., primary, secondary, success, danger). -4. **Card Components:** Style card-like components with class selectors to create consistent layouts. -5. **Navigation Menus:** Apply class selectors to style navigation menus, links, and buttons for a cohesive design. -6. **Form Elements:** Use class selectors to style form elements like input fields, checkboxes, and radio buttons. -7. **Alert Messages:** Style alert messages, notifications, or banners with class selectors for a consistent look and feel. - -By using class selectors in these scenarios, you can create a more organized and maintainable CSS structure for your web page. - -## Conclusion - -The class selector in CSS is a powerful tool for selecting and styling elements based on their class attributes. By using class selectors, you can apply consistent styles to groups of elements across your web page, making it easier to maintain and update the styles. It allows you to create reusable styles that can be applied to multiple elements, improving the consistency and maintainability of your CSS code. \ No newline at end of file diff --git a/docs/css/selectors/simple-selectors/element-selector.md b/docs/css/selectors/simple-selectors/element-selector.md deleted file mode 100644 index 4a329a739..000000000 --- a/docs/css/selectors/simple-selectors/element-selector.md +++ /dev/null @@ -1,182 +0,0 @@ ---- -id: element-selector -title: Element Selector -sidebar_label: Element Selector -sidebar_position: 1 -tags: - [ - element-selector, - css-selectors, - css, - selectors, - simple-selectors, - css-basics, - css-tutorial, - css-guide, - css-tutorial-for-beginners, - learn-css, - css-tutorial-for-beginners-2025, - css-tutorial-for-learning, - ] -description: The element selector is used to select elements on a web page based on their element type. -keywords: - [ - element selector, - css element selector, - css selectors, - css basics, - css tutorial, - css guide, - css tutorial for beginners, - learn css, - css tutorial for beginners 2025, - css tutorial for learning, - ] ---- - -In CSS, the element selector is used to select elements on a web page based on their element type. It is one of the simplest and most commonly used selectors in CSS. - - - -## What is an Element Selector? - -An element selector selects all elements on a web page that match a specified element type. It targets HTML elements based on their tag name. For example, to select all `

` elements on a page, you would use the following CSS rule: - -```css title="styles.css" -p { - color: red; -} -``` - -In this example, the CSS rule selects all `

` elements and sets their text color to red. The element selector is denoted by the tag name (`p` in this case) followed by curly braces `{}` containing the CSS properties and values to apply to the selected elements. - -## Syntax of the Element Selector - -The syntax of the element selector is as follows: - -```css title="styles.css" -element { - property: value; -} -``` - -Where: - -- `element`: Represents the tag name of the HTML element you want to target. -- `property`: Refers to the CSS property you want to apply to the selected elements. -- `value`: Specifies the value of the CSS property. -- `{}`: Encloses the CSS properties and values to be applied to the selected elements. -- `;`: Separates multiple CSS properties within the rule. - -The element selector can be used to style various HTML elements, such as headings (`

`, `

`, etc.), paragraphs (`

`), links (``), lists (`