Skip to content

Commit 7eec850

Browse files
committed
mongoDB docs 15 to 20 added
1 parent 9421bda commit 7eec850

File tree

6 files changed

+602
-0
lines changed

6 files changed

+602
-0
lines changed

docs/MongoDB/mongodb-aggregation.md

Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,89 @@
1+
---
2+
id: mongodb-aggregation
3+
title: MongoDB - Aggregation
4+
sidebar_label: Aggregation
5+
sidebar_position: 19
6+
tags: [mongodb, aggregation, database, operations]
7+
description: Learn how to perform aggregation operations in MongoDB to process and compute data results.
8+
---
9+
10+
# MongoDB - Aggregation
11+
12+
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.
13+
14+
## The aggregate() Method
15+
16+
For aggregation in MongoDB, you should use the `aggregate()` method.
17+
18+
### Syntax
19+
20+
The basic syntax of the `aggregate()` method is as follows:
21+
22+
```shell
23+
>db.COLLECTION_NAME.aggregate(AGGREGATE_OPERATION)
24+
```
25+
26+
### Example
27+
28+
In the collection, you have the following data:
29+
30+
```json
31+
[
32+
{
33+
"_id": ObjectId("7df78ad8902c"),
34+
"title": "MongoDB Overview",
35+
"description": "MongoDB is a NoSQL database",
36+
"by_user": "tutorials point",
37+
"url": "http://www.tutorialspoint.com",
38+
"tags": ["mongodb", "database", "NoSQL"],
39+
"likes": 100
40+
},
41+
{
42+
"_id": ObjectId("7df78ad8902d"),
43+
"title": "NoSQL Overview",
44+
"description": "NoSQL database is very fast",
45+
"by_user": "tutorials point",
46+
"url": "http://www.tutorialspoint.com",
47+
"tags": ["mongodb", "database", "NoSQL"],
48+
"likes": 10
49+
},
50+
{
51+
"_id": ObjectId("7df78ad8902e"),
52+
"title": "Neo4j Overview",
53+
"description": "Neo4j is a NoSQL database",
54+
"by_user": "Neo4j",
55+
"url": "http://www.neo4j.com",
56+
"tags": ["neo4j", "database", "NoSQL"],
57+
"likes": 750
58+
}
59+
]
60+
```
61+
62+
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:
63+
64+
```shell
65+
> db.mycol.aggregate([{$group : {_id : "$by_user", num_tutorial : {$sum : 1}}}])
66+
{ "_id" : "tutorials point", "num_tutorial" : 2 }
67+
{ "_id" : "Neo4j", "num_tutorial" : 1 }
68+
```
69+
70+
In the above example, we have grouped documents by the field `by_user` and counted the number of tutorials written by each user.
71+
72+
## Aggregation Expressions
73+
74+
Here are some common aggregation expressions used with the `aggregate()` method:
75+
76+
| Expression | Description | Example |
77+
|------------|-------------|---------|
78+
| $sum | Sums up the defined value from all documents in the collection. | `db.mycol.aggregate([{$group : {_id : "$by_user", num_tutorial : {$sum : "$likes"}}}])` |
79+
| $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"}}}])` |
80+
| $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"}}}])` |
81+
| $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"}}}])` |
82+
| $push | Inserts the value into an array in the resulting document. | `db.mycol.aggregate([{$group : {_id : "$by_user", url : {$push: "$url"}}}])` |
83+
| $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"}}}])` |
84+
| $first | Gets the first document from the source documents according to the grouping. | `db.mycol.aggregate([{$group : {_id : "$by_user", first_url : {$first : "$url"}}}])` |
85+
| $last | Gets the last document from the source documents according to the grouping. | `db.mycol.aggregate([{$group : {_id : "$by_user", last_url : {$last : "$url"}}}])` |
86+
87+
## Pipeline Concept
88+
89+
MongoDB supports the pipeline concept in the aggregation framework, similar to UNIX command shell pipelines. The pipeline allows executing operations on input data

docs/MongoDB/mongodb-indexing.md

Lines changed: 180 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,180 @@
1+
---
2+
id: mongodb-indexing
3+
title: MongoDB - Indexing
4+
sidebar_label: Indexing
5+
sidebar_position: 18
6+
tags: [mongodb, indexing, database, commands]
7+
description: Learn how to create and manage indexes in MongoDB to improve query performance.
8+
---
9+
10+
# MongoDB - Indexing
11+
12+
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.
13+
14+
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.
15+
16+
## The createIndex() Method
17+
18+
To create an index, you need to use the `createIndex()` method of MongoDB.
19+
20+
### Syntax
21+
22+
The basic syntax of the `createIndex()` method is as follows:
23+
24+
```shell
25+
>db.COLLECTION_NAME.createIndex({KEY:1})
26+
```
27+
28+
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`.
29+
30+
### Example
31+
32+
```shell
33+
>db.mycol.createIndex({"title":1})
34+
{
35+
"createdCollectionAutomatically" : false,
36+
"numIndexesBefore" : 1,
37+
"numIndexesAfter" : 2,
38+
"ok" : 1
39+
}
40+
```
41+
42+
In the `createIndex()` method, you can pass multiple fields to create an index on multiple fields.
43+
44+
```shell
45+
>db.mycol.createIndex({"title":1,"description":-1})
46+
```
47+
48+
## Index Options
49+
50+
This method also accepts a list of options (which are optional). Following is the list:
51+
52+
| Parameter | Type | Description |
53+
|---------------------|----------|-----------------------------------------------------------------------------------------------------------------------------------|
54+
| background | Boolean | Builds the index in the background so that building an index does not block other database activities. Default value is `false`. |
55+
| 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`. |
56+
| 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. |
57+
| 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`. |
58+
| expireAfterSeconds | Integer | Specifies a value, in seconds, as a TTL to control how long MongoDB retains documents in this collection. |
59+
| 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. |
60+
| 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`. |
61+
| 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`. |
62+
63+
## The dropIndex() Method
64+
65+
You can drop a particular index using the `dropIndex()` method of MongoDB.
66+
67+
### Syntax
68+
69+
The basic syntax of the `dropIndex()` method is as follows:
70+
71+
```shell
72+
>db.COLLECTION_NAME.dropIndex({KEY:1})
73+
```
74+
75+
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:
76+
77+
```shell
78+
dropIndex("name_of_the_index")
79+
```
80+
81+
### Example
82+
83+
```shell
84+
> db.mycol.dropIndex({"title":1})
85+
{
86+
"ok" : 0,
87+
"errmsg" : "can't find index with key: { title: 1.0 }",
88+
"code" : 27,
89+
"codeName" : "IndexNotFound"
90+
}
91+
```
92+
93+
## The dropIndexes() Method
94+
95+
This method deletes multiple (specified) indexes on a collection.
96+
97+
### Syntax
98+
99+
The basic syntax of the `dropIndexes()` method is as follows:
100+
101+
```shell
102+
>db.COLLECTION_NAME.dropIndexes()
103+
```
104+
105+
### Example
106+
107+
Assume we have created 2 indexes in the named `mycol` collection as shown below:
108+
109+
```shell
110+
> db.mycol.createIndex({"title":1,"description":-1})
111+
```
112+
113+
Following example removes the above-created indexes of `mycol`:
114+
115+
```shell
116+
>db.mycol.dropIndexes({"title":1,"description":-1})
117+
{ "nIndexesWas" : 2, "ok" : 1 }
118+
```
119+
120+
## The getIndexes() Method
121+
122+
This method returns the description of all the indexes in the collection.
123+
124+
### Syntax
125+
126+
Following is the basic syntax of the `getIndexes()` method:
127+
128+
```shell
129+
db.COLLECTION_NAME.getIndexes()
130+
```
131+
132+
### Example
133+
134+
Assume we have created 2 indexes in the named `mycol` collection as shown below:
135+
136+
```shell
137+
> db.mycol.createIndex({"title":1,"description":-1})
138+
```
139+
140+
Following example retrieves all the indexes in the collection `mycol`:
141+
142+
```shell
143+
> db.mycol.getIndexes()
144+
[
145+
{
146+
"v" : 2,
147+
"key" : {
148+
"_id" : 1
149+
},
150+
"name" : "_id_",
151+
"ns" : "test.mycol"
152+
},
153+
{
154+
"v" : 2,
155+
"key" : {
156+
"title" : 1,
157+
"description" : -1
158+
},
159+
"name" : "title_1_description_-1",
160+
"ns" : "test.mycol"
161+
}
162+
]
163+
```
164+
165+
## Diagram
166+
167+
```mermaid
168+
graph TD;
169+
A["Start"] --> B["Specify Collection"]
170+
B --> C{"Create Index"}
171+
C -->|Single Field| D["createIndex({KEY:1})"]
172+
C -->|Multiple Fields| E["createIndex({KEY1:1, KEY2:-1})"]
173+
D --> F["Index Created"]
174+
E --> F["Index Created"]
175+
F --> G["Use Index in Queries"]
176+
G --> H["End"]
177+
```
178+
179+
## Note
180+
> 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.

docs/MongoDB/mongodb-limit-records.md

Lines changed: 99 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,99 @@
1+
---
2+
id: mongodb-limit-records
3+
title: MongoDB - Limit Records
4+
sidebar_label: Limit Records
5+
sidebar_position: 16
6+
tags: [mongodb, limit, records, commands]
7+
description: Learn how to limit the number of records returned in a MongoDB query using the limit() method.
8+
---
9+
10+
# MongoDB - Limit Records
11+
12+
In this chapter, we will learn how to limit records using MongoDB.
13+
14+
## The limit() Method
15+
16+
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.
17+
18+
### Syntax
19+
20+
The basic syntax of the `limit()` method is as follows:
21+
22+
```bash
23+
> db.COLLECTION_NAME.find().limit(NUMBER)
24+
```
25+
26+
### Example
27+
28+
Consider the collection `mycol` has the following data:
29+
30+
```json
31+
{ "_id" : ObjectId("507f191e810c19729de860e1"), "title": "MongoDB Overview" }
32+
{ "_id" : ObjectId("507f191e810c19729de860e2"), "title": "NoSQL Overview" }
33+
{ "_id" : ObjectId("507f191e810c19729de860e3"), "title": "Tutorials Point Overview" }
34+
```
35+
36+
The following example will display only two documents while querying the document:
37+
38+
```bash
39+
> db.mycol.find({},{"title":1,_id:0}).limit(2)
40+
{"title":"MongoDB Overview"}
41+
{"title":"NoSQL Overview"}
42+
```
43+
44+
If you don't specify the number argument in the `limit()` method, it will display all documents from the collection.
45+
46+
## MongoDB skip() Method
47+
48+
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.
49+
50+
### Syntax
51+
52+
The basic syntax of the `skip()` method is as follows:
53+
54+
```bash
55+
> db.COLLECTION_NAME.find().limit(NUMBER).skip(NUMBER)
56+
```
57+
58+
### Example
59+
60+
The following example will display only the second document:
61+
62+
```bash
63+
> db.mycol.find({},{"title":1,_id:0}).limit(1).skip(1)
64+
{"title":"NoSQL Overview"}
65+
```
66+
67+
Please note, the default value in the `skip()` method is 0.
68+
69+
## Diagram
70+
71+
### Limit and Skip Operation Flow
72+
```mermaid
73+
graph TD;
74+
A[Start] --> B[Specify Collection]
75+
B --> C{Set Limit}
76+
C -->|Yes| D[Apply limit Method]
77+
D --> E{Set Skip}
78+
E -->|Yes| F[Apply skip Method]
79+
E -->|No| G[Execute find with Limit]
80+
F --> G[Execute find with Limit and Skip]
81+
G --> H[Display Results]
82+
H --> I[End]
83+
```
84+
85+
## Notes
86+
87+
> - The `limit()` method is used to restrict the number of documents returned in the query result.
88+
> - The `skip()` method is used to skip a specified number of documents in the query result.
89+
> - Combining `limit()` and `skip()` allows for pagination of results.
90+
> - The default value for `skip()` is 0, meaning no documents are skipped.
91+
92+
## Table of Commands
93+
94+
| Command | Description |
95+
| ------- | ----------- |
96+
| `db.COLLECTION_NAME.find().limit(NUMBER)` | Limits the number of documents returned. |
97+
| `db.COLLECTION_NAME.find().limit(NUMBER).skip(NUMBER)` | Limits and skips the number of documents returned. |
98+
| `db.COLLECTION_NAME.find({}, {"title": 1, "_id": 0}).limit(2)` | Retrieves two documents with only the `title` field. |
99+
| `db.COLLECTION_NAME.find({}, {"title": 1, "_id": 0}).limit(1).skip(1)` | Retrieves the second document with only the `title` field. |

0 commit comments

Comments
 (0)