Skip to content

Commit 3e15b8d

Browse files
authored
Merge pull request #1468 from Vipullakum007/php-basics-docs
Php basics docs added
2 parents 6f4b8a5 + 3064e95 commit 3e15b8d

14 files changed

+1020
-0
lines changed
Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
---
2+
id: mongodb-ObjectId
3+
title: MongoDB - ObjectId
4+
sidebar_label: ObjectId
5+
sidebar_position: 8
6+
tags: [mongodb, ObjectId, document identifier]
7+
description: Understand the structure and usage of ObjectId in MongoDB, including creation, timestamp extraction, and conversion to string format.
8+
---
9+
10+
We have been using MongoDB ObjectId in all the previous chapters. In this chapter, let's delve into the structure and usage of ObjectId.
11+
12+
## ObjectId Structure
13+
14+
An ObjectId is a 12-byte BSON type structured as follows:
15+
16+
- The first 4 bytes represent the seconds since the Unix epoch.
17+
- The next 3 bytes are the machine identifier.
18+
- The following 2 bytes consist of the process id.
19+
- The last 3 bytes are a random counter value.
20+
21+
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.
22+
23+
## Creating New ObjectId
24+
25+
To generate a new ObjectId, use the following code snippet:
26+
27+
```javascript
28+
newObjectId = ObjectId()
29+
```
30+
31+
The above statement will return a uniquely generated id like:
32+
33+
```
34+
ObjectId("5349b4ddd2781d08c09890f3")
35+
```
36+
37+
Alternatively, you can provide a 12-byte id explicitly:
38+
39+
```javascript
40+
myObjectId = ObjectId("5349b4ddd2781d08c09890f4")
41+
```
42+
43+
## Creating Timestamp of a Document
44+
45+
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:
46+
47+
```javascript
48+
ObjectId("5349b4ddd2781d08c09890f4").getTimestamp()
49+
```
50+
51+
This will return the creation time of the document in ISO date format:
52+
53+
```
54+
ISODate("2014-04-12T21:49:17Z")
55+
```
56+
57+
## Converting ObjectId to String
58+
59+
In certain scenarios, you may require the ObjectId value in a string format. To convert the ObjectId to a string, use the following code:
60+
61+
```javascript
62+
newObjectId.str
63+
```
64+
65+
The above code will provide the string format of the ObjectId, such as:
66+
67+
```
68+
5349b4ddd2781d08c09890f3
69+
```
Lines changed: 109 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,109 @@
1+
---
2+
id: mongodb-indexing-limitations
3+
title: MongoDB - Indexing Limitations
4+
sidebar_label: Indexing Limitations
5+
sidebar_position: 7
6+
tags: [mongodb, indexing, limitations, performance]
7+
description: Understand the limitations of indexing in MongoDB, including overhead, RAM usage, query constraints, and key limits.
8+
---
9+
10+
# MongoDB - Indexing Limitations
11+
12+
In this chapter, we will learn about Indexing Limitations and its other components.
13+
14+
## Extra Overhead
15+
16+
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.
17+
18+
:::note
19+
- Indexes require additional space.
20+
- Each insert, update, and delete operation requires additional processing due to index maintenance.
21+
:::
22+
23+
```mermaid
24+
graph TD;
25+
A[Insert Operation] --> B[Index Overhead];
26+
C[Update Operation] --> B;
27+
D[Delete Operation] --> B;
28+
```
29+
30+
## RAM Usage
31+
32+
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.
33+
34+
:::note
35+
Ensure that the total size of all indexes does not exceed the available RAM to avoid performance issues.
36+
:::
37+
38+
```mermaid
39+
graph TD;
40+
A[Indexes] -->|Stored in| B[RAM];
41+
B -->|Exceeds| C[Performance Loss];
42+
C --> D[Deletes Some Indexes];
43+
```
44+
45+
## Query Limitations
46+
47+
Indexing can't be used in queries which use:
48+
- Regular expressions or negation operators like `$nin`, `$not`, etc.
49+
- Arithmetic operators like `$mod`, etc.
50+
- `$where` clause
51+
52+
:::note
53+
- Regular expressions and negation operators cannot use indexes.
54+
- Arithmetic operators and `$where` clause cannot use indexes.
55+
:::
56+
57+
| Query Type | Index Usage |
58+
|-----------------|--------------|
59+
| Regular Expressions | Not Supported |
60+
| Negation Operators | Not Supported |
61+
| Arithmetic Operators | Not Supported |
62+
| `$where` Clause | Not Supported |
63+
64+
## Index Key Limits
65+
66+
Starting from version 2.6, MongoDB will not create an index if the value of existing index field exceeds the index key limit.
67+
68+
> **Note:** Index creation is restricted if any field value exceeds the index key limit.
69+
70+
```mermaid
71+
graph TD;
72+
A[Index Creation] -->|Value exceeds limit| B[Not Created];
73+
```
74+
75+
## Inserting Documents Exceeding Index Key Limit
76+
77+
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.
78+
79+
:::note
80+
Documents with indexed field values exceeding the key limit will not be inserted into an indexed collection.
81+
:::
82+
83+
```mermaid
84+
graph TD;
85+
A[Document Insertion] -->|Exceeds Key Limit| B[Insertion Failed];
86+
C[mongorestore] -->|Exceeds Key Limit| B;
87+
D[mongoimport] -->|Exceeds Key Limit| B;
88+
```
89+
90+
## Maximum Ranges
91+
92+
- A collection cannot have more than 64 indexes.
93+
- The length of the index name cannot be longer than 125 characters.
94+
- A compound index can have a maximum of 31 fields indexed.
95+
96+
> **Table: Maximum Ranges**
97+
98+
| Limit Type | Maximum Value |
99+
|--------------------------|---------------------|
100+
| Number of Indexes | 64 |
101+
| Length of Index Name | 125 Characters |
102+
| Fields in Compound Index | 31 Fields |
103+
104+
```mermaid
105+
graph TD;
106+
A[Maximum Ranges] --> B[64 Indexes per Collection];
107+
A --> C[125 Characters Index Name];
108+
A --> D[31 Fields in Compound Index];
109+
```
Lines changed: 109 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,109 @@
1+
---
2+
id: mongodb-map-reduce
3+
title: MongoDB - Map Reduce
4+
sidebar_label: Map Reduce
5+
sidebar_position: 9
6+
tags: [mongodb, map reduce, data processing]
7+
description: Understand the MapReduce paradigm in MongoDB for condensing large volumes of data into useful aggregated results.
8+
---
9+
10+
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.
11+
12+
## MapReduce Command Syntax
13+
14+
The basic syntax of the `mapReduce` command in MongoDB is as follows:
15+
16+
```javascript
17+
db.collection.mapReduce(
18+
function() {emit(key,value);}, // map function
19+
function(key,values) {return reduceFunction;}, // reduce function
20+
{ // options
21+
out: collection, // specifies the location of the query result
22+
query: document, // optional selection criteria for documents
23+
sort: document, // optional sort criteria
24+
limit: number // optional maximum number of documents to return
25+
}
26+
)
27+
```
28+
29+
In the above syntax:
30+
31+
- `map` is a JavaScript function that maps a value with a key and emits a key-value pair.
32+
- `reduce` is a JavaScript function that reduces or groups documents with the same key.
33+
- `out` specifies the location of the map-reduce query result.
34+
- `query` specifies optional selection criteria for selecting documents.
35+
- `sort` specifies optional sort criteria.
36+
- `limit` specifies the optional maximum number of documents to return.
37+
38+
### Using MapReduce
39+
40+
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.
41+
42+
```javascript
43+
db.posts.mapReduce(
44+
function() { emit(this.user_name, 1); },
45+
function(key, values) { return Array.sum(values); },
46+
{
47+
query: { status: "active" },
48+
out: "post_total"
49+
}
50+
)
51+
```
52+
53+
The above mapReduce query outputs the following result:
54+
55+
```json
56+
{
57+
"result" : "post_total",
58+
"timeMillis" : 9,
59+
"counts" : {
60+
"input" : 4,
61+
"emit" : 4,
62+
"reduce" : 2,
63+
"output" : 2
64+
},
65+
"ok" : 1
66+
}
67+
```
68+
69+
To see the result of this mapReduce query, you can use the `find` operator:
70+
71+
```javascript
72+
db.post_total.find()
73+
```
74+
75+
This query will return results showing the count of active posts for each user:
76+
77+
```json
78+
{ "_id" : "tom", "value" : 2 }
79+
{ "_id" : "mark", "value" : 2 }
80+
```
81+
82+
MapReduce queries in MongoDB are powerful for constructing complex aggregation queries using custom JavaScript functions, providing flexibility in data processing and analysis.
83+
84+
### Diagram: MapReduce Process
85+
86+
```mermaid
87+
graph TD;
88+
A[Query Collection] --> B(Map Function);
89+
B --> C(Emit Key-Value Pairs);
90+
C --> D(Reduce Function);
91+
D --> E(Aggregated Results);
92+
```
93+
94+
:::note Performance Considerations
95+
96+
When using MapReduce in MongoDB:
97+
- Consider the performance overhead, especially for large data sets.
98+
- Optimize your map and reduce functions for efficiency.
99+
- Utilize indexes to improve query performance.
100+
:::
101+
102+
### Table: MapReduce Options
103+
104+
| Option | Description |
105+
|--------|------------------------------------------------|
106+
| out | Specifies the location of the query result. |
107+
| query | Optional selection criteria for documents. |
108+
| sort | Optional sort criteria. |
109+
| limit | Optional maximum number of documents to return|
Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
---
2+
id: mongodb-regular-expression
3+
title: MongoDB - Regular Expression
4+
sidebar_label: Regular Expression
5+
sidebar_position: 11
6+
tags: [mongodb, regular expression, pattern matching]
7+
description: Learn how to use regular expressions for pattern matching in MongoDB using the $regex operator.
8+
---
9+
10+
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.
11+
12+
## Using Regular Expressions
13+
14+
Assume we have a document in the `posts` collection:
15+
16+
```javascript
17+
db.posts.insert({
18+
"post_text": "enjoy the mongodb articles on tutorialspoint",
19+
"tags": ["mongodb", "tutorialspoint"]
20+
})
21+
```
22+
23+
To search for posts containing the string "tutorialspoint" in their `post_text` field using a regular expression:
24+
25+
```javascript
26+
db.posts.find({ post_text: { $regex: "tutorialspoint" } }).pretty()
27+
```
28+
29+
### Diagram: Regular Expression Query Process
30+
31+
```mermaid
32+
graph LR;
33+
A[Query Collection] --> B(Regex Pattern Matching);
34+
B --> C(Retrieve Matching Documents);
35+
```
36+
37+
### Note: Case Insensitive Search
38+
39+
To perform a case-insensitive search, use the $options parameter with value "$i" in the regex query:
40+
41+
```javascript
42+
db.posts.find({ post_text: { $regex: "tutorialspoint", $options: "$i" } })
43+
```
44+
45+
### Using Regex for Array Elements
46+
47+
Regular expressions can also be applied to array fields, such as searching for posts with tags starting from "tutorial":
48+
49+
```javascript
50+
db.posts.find({ tags: { $regex: "tutorial" } })
51+
```
52+
53+
### Optimizing Regex Queries
54+
55+
- Indexed fields improve the performance of regular expression queries by using indexed values for matching.
56+
- Prefix expressions in regular expressions, like "^tut," optimize searches by matching strings starting with specific characters.
57+
58+
## Table: Regex Search Options
59+
60+
| Option | Description |
61+
|--------------|----------------------------------------------------------------|
62+
| $regex | Operator for regular expression pattern matching. |
63+
| $options | Optional parameter for regex options like case insensitivity. |
64+
| ^ | Anchor for matching the start of a string. |
65+
| $ | Anchor for matching the end of a string. |

0 commit comments

Comments
 (0)