Fix typos

This commit is contained in:
Marcello 2021-09-20 19:35:32 +02:00
parent 76550dfa3c
commit 5c0799df7f
118 changed files with 1150 additions and 1602 deletions

View file

@ -2,7 +2,7 @@
The database is a container of **collections**. The collections are containers of **documents**.
The documents are _schema-less_ that is they have a dynamic structure that can change between documents in the same colletion.
The documents are _schema-less_ that is they have a dynamic structure that can change between documents in the same collection.
## Data Types
@ -17,7 +17,7 @@ The documents are _schema-less_ that is they have a dynamic structure that can c
| Embedded Document | `{"a": {...}}` |
| Embedded Array | `{"b": [...]}` |
It's mandatory for each document ot have an uniwue field `_id`.
It's mandatory for each document ot have an unique field `_id`.
MongoDB automatically creates an `ObjectId()` if it's not provided.
## Databases & Collections Usage
@ -69,7 +69,7 @@ db.<collection>.insertOne({document}) # implicit collection creation
`$<key>` is used to access the value of the field dynamically
```json
{ "$expr": { <expression> } } // aggregetion expresion, variables, conditional expressions
{ "$expr": { <expression> } } // aggregation expression, variables, conditional expressions
{ "$expr": { "$comparison_operator": [ "$<key>", "$<key>" ] } } // compare field values
```
@ -80,13 +80,13 @@ db.<collection>.insertOne({document}) # implicit collection creation
It's possible to insert a single document with the command `insertOne()` or multiple documents with `insertMany()`.
Isertion results:
Insertion results:
- error -> rollback
- success -> entire documents gets saved
```sh
# explicit collection creation, all options are otional
# explicit collection creation, all options are optional
db.createCollection( <name>,
{
capped: <boolean>,
@ -121,7 +121,7 @@ db.<collection>.insertMany([ { document }, { document } ] , { "ordered": false }
```sh
db.<collection>.findOne() # find only one document
db.<collection>.find(filter) # show selected documents
db.<collection>.find(filter, {"<key>": 1}) # show selected values form documents (1 or true => show, 0 or false => dont show, cant mix 0 and 1)
db.<collection>.find(filter, {"<key>": 1}) # show selected values form documents (1 or true => show, 0 or false => don't show, cant mix 0 and 1)
db.<collection>.find(filter, {_id: 0, "<key>": 1}) # only _id can be set to 0 with other keys at 1
db.<collection>.find().pretty() # show documents formatted
db.<collection>.find().limit(n) # show n documents
@ -155,7 +155,7 @@ db.<collection>.find().hint( { $natural : -1 } ) # force the query to perform a
```sh
db.<collection>.updateOne(filter, $set: {"<key>": value}) # add or modify values
db.<collection>.updateOne(filter, $set: {"<key>": value}, {upsert: true}) # add or modify values, if attribute doesent exists create it
db.<collection>.updateOne(filter, $set: {"<key>": value}, {upsert: true}) # add or modify values, if attribute doesn't exists create it
db.<collection>.updateMany(filter, update)
@ -175,7 +175,7 @@ db.dropDatabase() # delete entire database
## [Mongoimport](https://docs.mongodb.com/database-tools/mongoimport/)
Utility to import all docs into a specified collection.
If the collection alredy exists `--drop` deletes it before reuploading it.
If the collection already exists `--drop` deletes it before reuploading it.
**WARNING**: CSV separators must be commas (`,`)
```sh
@ -228,17 +228,17 @@ mongoexport --collection=<collection> <options> <connection-string>
**Nested / Embedded Documents**:
- Group data locically
- Group data logically
- Optimal for data belonging together that do not overlap
- Should avoid nesting too deep or making too long arrays (max doc size 16 mb)
```json
{
_id: Objectid()
"_id": Objectid()
"<key>": "value"
"<key>": "value"
innerDocument: {
"innerDocument": {
"<key>": "value"
"<key>": "value"
}
@ -249,19 +249,19 @@ mongoexport --collection=<collection> <options> <connection-string>
- Divide data between collections
- Optimal for related but shared data used in relations or stand-alone
- Allows to overtake nidification and size limits
- Allows to overtake nesting and size limits
NoSQL databases do not have relations and references. It's the app that has to handle them.
```json
{
"<key>": "value"
references: ["id1", "id2"]
"references": ["id1", "id2"]
}
// referenced
{
_id: "id1"
"_id": "id1"
"<key>": "value"
}
```
@ -273,7 +273,7 @@ Indexes support the efficient execution of queries in MongoDB.
Without indexes, MongoDB must perform a _collection scan_ (_COLLSCAN_): scan every document in a collection, to select those documents that match the query statement.
If an appropriate index exists for a query, MongoDB can use the index to limit the number of documents it must inspect (_IXSCAN_).
Indexes are special data structures that store a small portion of the collections 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. The ordering of the index entries supports efficient equality matches and range-based query operations. In addition, MongoDB can return sorted results by using the ordering in the index.
Indexes are special data structures that store a small portion of the collection's 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. The ordering of the index entries supports efficient equality matches and range-based query operations. In addition, MongoDB can return sorted results by using the ordering in the index.
Indexes _slow down writing operations_ since the index must be updated at every writing.
@ -283,13 +283,13 @@ Indexes _slow down writing operations_ since the index must be updated at every
- **Normal**: Fields sorted by name
- **Compound**: Multiple Fields sorted by name
- **Multykey**: values of sorted arrays
- **Multikey**: values of sorted arrays
- **Text**: Ordered text fragments
- **Geospatial**: ordered geodata
**Sparse** indexes only contain entries for documents that have the indexed field, even if the index field contains a null value. The index skips over any document that is missing the indexed field.
### Diagnosys and query planning
### Diagnosis and query planning
```sh
db.<collection>.find({...}).explain() # explain won't accept other functions
@ -345,9 +345,9 @@ Profiling Levels:
Logs are saved in the `system.profile` _capped_ collection.
```sh
db.setProgilingLevel(n) # set profiler level
db.setProfilingLevel(n) # set profiler level
db.setProfilingLevel(1, { slowms: <ms> })
db.getProfilingStatus() # check profiler satus
db.getProfilingStatus() # check profiler status
db.system.profile.find().limit(n).sort( {} ).pretty() # see logs
db.system.profile.find().limit(n).sort( { ts : -1 } ).pretty() # sort by decreasing timestamp
@ -358,7 +358,7 @@ db.system.profile.find().limit(n).sort( { ts : -1 } ).pretty() # sort by decrea
**Authentication**: identifies valid users
**Authorization**: identifies what a user can do
- **userAdminAnyDatabase**: can admin every db in the istance (role must be created on admin db)
- **userAdminAnyDatabase**: can admin every db in the instance (role must be created on admin db)
- **userAdmin**: can admin the specific db in which is created
- **readWrite**: can read and write in the specific db in which is created
- **read**: can read the specific db in which is created
@ -391,7 +391,7 @@ db.createUser(
## Sharding
**Sharding** is a MongoDB concept through which big datasests are subdivided in smaller sets and distribuited towards multiple instances of MongoDB.
**Sharding** is a MongoDB concept through which big datasets are subdivided in smaller sets and distributed towards multiple instances of MongoDB.
It's a technique used to improve the performances of large queries towards large quantities of data that require al lot of resources from the server.
A collection containing several documents is splitted in more smaller collections (_shards_)
@ -400,7 +400,7 @@ Shards are implemented via cluster that are none other a group of MongoDB instan
Shard components are:
- Shards (min 2), instances of MongoDB that contain a subset of the data
- A config server, instasnce of MongoDB which contains metadata on the cluster, that is the set of instances that have the shard data.
- A config server, instance of MongoDB which contains metadata on the cluster, that is the set of instances that have the shard data.
- A router (or `mongos`), instance of MongoDB used to redirect the user instructions from the client to the correct server.
![Shared Cluster](../.images/mongodb_shared-cluster.png "Components of a shared cluster")
@ -413,7 +413,7 @@ A **replica set** in MongoDB is a group of `mongod` processes that maintain the
Sequence of operations applied to a collection as a _pipeline_ to get a result: `db.collection.aggregate(pipeline, options)`.
[Aggragations Stages][aggeregation_stages_docs]:
[Aggregations Stages][aggeregation_stages_docs]:
- `$lookup`: Right Join
- `$match`: Where

View file

@ -45,7 +45,7 @@ RPUSH <key> <value1> <value2> ... # add one or more values to the end of the lis
LPUSH <key> <value1> <value2> ... # add one or more values to the start of a list
LLEN # number of items in the list
LRANGE <key> <start_index> <end_index> # return a subset of the list, end index included. Negative indexes caout backwards from the end
LRANGE <key> <start_index> <end_index> # return a subset of the list, end index included. Negative indexes count backwards from the end
LPOP # remove and return the first item fro the list
RPOP # remove and return the last item fro the list
@ -56,7 +56,7 @@ RPOP # remove and return the last item fro the list
A set is similar to a list, except it does not have a specific order and each element may only appear once.
```sh
SADD <key> <value1> <value2> ... # add one or more values to the set (retunr 0 if values are alredy inside)
SADD <key> <value1> <value2> ... # add one or more values to the set (return 0 if values are already inside)
SREM <key> <value> # remove the given member from the set, return 1 or 0 to signal if the member was actually there or not.
SPOP <key> <value> # remove and return value from the set
@ -97,7 +97,7 @@ HGET <key> <field> # get data on a single field
HKEYS <key> # get all the fields in a hash
HVALS <key> # get all the values in a hash
HDEL <key> <field_1> <field_2> ... # delete one or more field hases
HDEL <key> <field_1> <field_2> ... # delete one or more field hashes
HMGET <key> <field> [<field> ...] # get the values of all the given hash fields
HMSET <key> <field> <value> [<field> <value> ...] # set multiple hash fields to multiple values

View file

@ -6,7 +6,7 @@
```sql
show databases; -- mostra database
CREATE DATABASE <database>; -- dataabse creation
CREATE DATABASE <database>; -- database creation
use <database_name>; -- usa un database particolare
exit; -- exit mysql
@ -67,7 +67,7 @@ ALTER TABLE <table>
```sql
INSERT INTO <table> (field_1, ...) VALUES (value_1, ...), (value_1, ...);
INSERT INTO <table> VALUES (value_1, ...), (value_1, ...); -- field order MUST respest tables's columns order
INSERT INTO <table> VALUES (value_1, ...), (value_1, ...); -- field order MUST respect tables's columns order
```
### Data Update
@ -93,36 +93,36 @@ SHOW columns FROM <table>; -- show table columns
DESCRIBE <table>; -- shows table
```
### Alias Tabelle
### Alias
```sql
SELECT <field/funzione> as <alias>; -- mostra <field/funzione> con nome <alias>
SELECT <field> as <alias>; -- shows <field/funzione> with name <alias>
```
### Selezione Condizionale
### Conditional Selection
```sql
SELECT * FROM <table> WHERE <condition>; -- mostra elementi che rispettano la condizione
AND, OR, NOT -- connettivi logici
SELECT * FROM <table> WHERE <condition>; -- shows elements that satisfy the condition
AND, OR, NOT -- logic connectors
SELECT * FROM <table> WHERE <field> Between <value_1> AND <value_2>;
```
### Ordinamento
### Ordering
```sql
SELECT * FROM <table> ORDER BY <field>, ...; -- mostra tabella ordinata in base a colonna <field>
SELECT * FROM <table> ORDER BY <field>, ... DESC; -- mostra tabella ordinata decrescente in base a colonna <field>
SELECT * FROM <table> ORDER BY <field>, ... LIMIT n; -- mostra tabella ordinata in base a colonna <field>, mostra n elementi
SELECT * FROM <table> ORDER BY <field>, ...; -- shows the table ordered by <field>
SELECT * FROM <table> ORDER BY <field>, ... DESC; -- shows the table ordered by <field>, decreasing order
SELECT * FROM <table> ORDER BY <field>, ... LIMIT n; -- shows the table ordered by <field>, shows n items
SELECT TOP(n) * FROM <table> ORDER BY <field>, ...; -- T-SQL
```
## Raggruppamento
## Grouping
```sql
SELECT * FROM <table> GROUP BY <field>;
SELECT * FROM <table> GROUP BY <field> HAVING <condition>;
SELECT DISTINCT <field> FROM <table>; -- mostra elementi senza riperizioni
SELECT DISTINCT <field> FROM <table>; -- shows elements without repetitions
```
### Ricerca caratteri in valori
@ -130,10 +130,10 @@ SELECT DISTINCT <field> FROM <table>; -- mostra elementi senza riperizioni
`%` 0+ caratteri
```sql
SELECT * FROM <table> WHERE <field> LIKE '<char>%'; -- seleziona elemnti in <field> inizianti per <char>
SELECT * FROM <table> WHERE <field> LIKE '%<char>'; -- seleziona elemnti in <field> terminanti per <char>
SELECT * FROM <table> WHERE <field> LIKE '%<char>%'; -- seleziona elemnti in <field> contenenti <char>
SELECT * FROM <table> WHERE <field> NOT LIKE '%<char>%'; -- seleziona elemnti in <field> non contenenti <char>
SELECT * FROM <table> WHERE <field> LIKE '<char>%'; -- selects items in <field> that start with <char>
SELECT * FROM <table> WHERE <field> LIKE '%<char>'; -- selects items in <field> that end with <char>
SELECT * FROM <table> WHERE <field> LIKE '%<char>%'; -- selects items in <field> that contain <char>
SELECT * FROM <table> WHERE <field> NOT LIKE '%<char>%'; -- selects items in <field> that do not contain <char>
```
### Selection from multiple tables
@ -143,18 +143,18 @@ SELECT a.<field>, b.<field> FROM <table> AS a, <table> AS b
WHERE a.<field> ...;
```
## Funzioni
## Functions
```sql
SELECT COUNT(*) FROM <field>; -- conta numero elemneti nel campo
SELECT MIN(*) FROM <table>; -- restituisce il valore minimo
SELECT MAX(*) FROM <table>; -- restituisce valore massimo
SELECT AVG(*) FROM <table>; -- media valori del campo
SELECT COUNT(*) FROM <field>; -- count of items in <field>
SELECT MIN(*) FROM <table>; -- min value
SELECT MAX(*) FROM <table>; -- max value
SELECT AVG(*) FROM <table>; -- mean of values
ALL (SELECT ...)
ANY (SELECT ...)
```
## Query Annidate
## Nested Queries
```sql
SELECT * FROM <table> WHERE EXISTS (SELECT * FROM <table>) -- selected field existing in subquery
@ -181,13 +181,10 @@ INSERT INTO <table>
## Join
Permette di legare due tabelle correlando i dati, le tabelle devono avere almeno un campo in comune.
Primary key deve comparire in altra tabella come foreign key.
```sql
SELECT * FROM <table1> JOIN <table2> ON <table1>.<field> = <table2>.<field>; -- seleziono tutti gli elementi che hanno una relarione tra le due tabelle
SELECT * FROM <table1> LEFT JOIN <table2> ON <condition>; -- seleziona tutti gli elementi di table1 e i eventuali elementi richiamati dal join
SELECT * FROM <table1> RIGHT JOIN <tabl2> ON <condition> -- -- seleziona tutti gli elementi di table2 e i eventuali elementi richiamati dal join
SELECT * FROM <table1> JOIN <table2> ON <table1>.<field> = <table2>.<field>;
SELECT * FROM <table1> LEFT JOIN <table2> ON <condition>;
SELECT * FROM <table1> RIGHT JOIN <table2> ON <condition>
```
[Inner Join, Left Join, Right Join, Full Outer Join](https://www.diffen.com/difference/Inner_Join_vs_Outer_Join)
@ -202,7 +199,7 @@ JOIN <table3> ON <table2>.<field> = <table3>.<field>;
[char, nchar, varchar, nvarchar](https://stackoverflow.com/questions/176514/what-is-the-difference-between-char-nchar-varchar-and-nvarchar-in-sql-server)
***
---
## T-SQL (MSSQL Server)
@ -230,7 +227,7 @@ DECLARE @var_name <type>
SET @var_name = <value>
-- use in query (memorize data)
SELECT @var_name = COUNT(*) -- query won't show results in the "table view" sice param is used in SELECT
SELECT @var_name = COUNT(*) -- query won't show results in the "table view" since param is used in SELECT
FROM <table> ...
-- display message (query won't show results in the "table view")
@ -263,7 +260,7 @@ CREATE PROCEDURE <Procedure_Name>
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from interfering with SELECT statements.
SET NOCOUNT ON; -- dont return number of selected rows
SET NOCOUNT ON; -- don't return number of selected rows
-- Insert statements for procedure here
SELECT ...