Skip to content

Php basics docs added #1468

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Jun 17, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
69 changes: 69 additions & 0 deletions docs/MongoDB/Advanced MongoDB/mongodb-ObjectId.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
---
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
```
109 changes: 109 additions & 0 deletions docs/MongoDB/Advanced MongoDB/mongodb-indexing-limitations.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
---
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];
```
109 changes: 109 additions & 0 deletions docs/MongoDB/Advanced MongoDB/mongodb-map-reduce.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
---
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|
65 changes: 65 additions & 0 deletions docs/MongoDB/Advanced MongoDB/mongodb-regular-expression.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
---
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. |
Loading
Loading