Mongo DB part 1
Install mongo with these instructions for Ubuntu:
[Link]
Follow these instruccions for Windows:
[Link]
Moreover, here it is a good tutorial:
[Link]
MongoDB comass - GUI for Mongo
[Link]
Start using Mongo (Linux)
Run mongo
sudo systemctl start mongod
Verify that MongoDB has started successfully.
sudo systemctl status mongod
Use mongo
mongosh
Use mongo compass
mongodb-compass
Con Docker
docker pull mongo
docker run --name some-mongo -d mongo
docker exec -it some-mongo bash
mongosh
Mongo DB documents
Records in MongoDB are documents, these are like json and have anf special _id
attribute.
Nested documents
Mongo Commands
Show databases
show dbs
Create a databse, if it doesn’t exist, it will be created (we need to insert then).
use myDB
To know wchich databaser we are using
db
Show collections (tables)
show collections
Insert
In order to reate a DB, we need to register a document(registro) in a colection(tabla). In
this case, we have three collections: user, books and authors.
[Link]({name: "Vicente Machaca", age: 100})
[Link]({ title:"The color of magic", author:"Terry
Pratchett", pages:300, rating:7, genres:["fantasy", "magic"]})
[Link]({ name:"Brandon Sanderson", age:60 })
[Link]( [{ title:"The light fantastics", author:"Terry
Pratchett", pages:250, rating:7, genres:["fantasy"]}, { title:"Dune",
author:"Frank Herbert", pages:500, rating:10, genres:["sci-fi",
"magic"]}] )
Find
Select all books collection
[Link]()
Select with filters. In this case, select all books where author is “Terry Pratchett”.
[Link]({ author:"Terry Pratchett" })
A more specific filter.
[Link]({ author:"Terry Pratchett", pages:300 })
[
{
_id: ObjectId("6413cae75bce717f77e1325b"),
title: 'The color of magic',
author: 'Terry Pratchett',
pages: 300,
rating: 7,
genres: [ 'fantasy', 'magic' ]
},
{
_id: ObjectId("6413cc635bce717f77e1325d"),
title: 'The light fantastics',
author: 'Terry Pratchett',
pages: 250,
rating: 7,
genres: [ 'fantasy' ]
}
]
[
{
_id: ObjectId("6413cae75bce717f77e1325b"),
title: 'The color of magic',
author: 'Terry Pratchett',
pages: 300,
rating: 7,
genres: [ 'fantasy', 'magic' ]
}
]
Select only some attributes.
[Link]({ author:"Terry Pratchett" }, {title:1, author:1})
[
{
_id: ObjectId("6413cae75bce717f77e1325b"),
title: 'The color of magic',
author: 'Terry Pratchett'
},
{
_id: ObjectId("6413cc635bce717f77e1325d"),
title: 'The light fantastics',
author: 'Terry Pratchett'
}
]
Select only title attribute
[Link]({}, {title:1})
[
{
_id: ObjectId("6413cae75bce717f77e1325b"),
title: 'The color of magic'
},
{
_id: ObjectId("6413cc635bce717f77e1325d"),
title: 'The light fantastics'
},
{
_id: ObjectId("6413cc635bce717f77e1325e"),
title: 'Dune'
}
]
Find - Count, limit, sorting
Select by id
[Link]({ _id:ObjectId("6413cae75bce717f77e1325b") })
{
_id: ObjectId("6413cae75bce717f77e1325b"),
title: 'The color of magic',
author: 'Terry Pratchett',
pages: 300,
rating: 7,
genres: [ 'fantasy', 'magic' ]
}
Count
[Link]( {author:"Terry Pratchett"} ).count()
Limit the result
[Link]().limit(2)
Sorting by title ascending (-1 for descending).
[Link]().sort( {title:1} )
[
{
_id: ObjectId("6413cc635bce717f77e1325e"),
title: 'Dune',
author: 'Frank Herbert',
pages: 500,
rating: 10,
genres: [ 'sci-fi', 'magic' ]
},
{
_id: ObjectId("6413cae75bce717f77e1325b"),
title: 'The color of magic',
author: 'Terry Pratchett',
pages: 300,
rating: 7,
genres: [ 'fantasy', 'magic' ]
},
{
_id: ObjectId("6413cc635bce717f77e1325d"),
title: 'The light fantastics',
author: 'Terry Pratchett',
pages: 250,
rating: 7,
genres: [ 'fantasy' ]
}
]
Sorting and limit
[Link]().sort( {title:-1} ).limit(2)
Ejercicios
Inserten 5 libros adicionales. Deben ser libros distintos y de su preferencia.
Muestren el título y autor de los libros que tengan como autor a 'Frank Herbert'
Cuenten la cantidad de libros que tengan 200 páginas.
Muestren una lista de libros que tengan 300 págínas y que esten ordenadas por autor.
Mongo DB part 2
Nested Documents
Example of nested documents
Insert a document with nested documents inside
[Link]({ title:"The Way of Kings", author:"Brandom
Sanderson", rating:9, pages:400, genres:["fantasy"],
reviews:[{name:"Yoshi", body:"Great book"}, {name:"Mario", body:"so
so"}] })
Insert many
[Link]([{ title:"Mi planta de naranja Lima", author:"Jose
Vasconcelos", rating:10, pages:400, genres:["fantasy"],
reviews:[{name:"Goku", body:"Great book :)"}, {name:"Vegeta",
body:"Bad"}] }, { title:"La psiquiatra", author:"Wulf Dorn", rating:9,
pages:500, genres:["Trhiller"], reviews:[{name:"Yoshi", body:"Great
book"}, {name:"Rochi", body:"Great book!!"} ]}])
Operators and complex queries
Find all books with rating greater than 9. $gt is the operatr greter than.
• $gt → greater than
• $gte → greater than or equal
• $lt → less than
• $lte → less than or equal
[Link]({ rating: {$gt:9} })
[
{
_id: ObjectId("6413cc635bce717f77e1325e"),
title: 'Dune',
author: 'Frank Herbert',
pages: 500,
rating: 10,
genres: [ 'sci-fi', 'magic' ]
},
{
_id: ObjectId("6414649eecd980628b90377a"),
title: 'Mi planta de naranja Lima',
author: 'Jose Vasconcelos',
rating: 10,
pages: 400,
genres: [ 'fantasy' ],
reviews: [
{ name: 'Goku', body: 'Great book :)' },
{ name: 'Vegeta', body: 'Bad' }
]
}
]
More filters:
[Link]( { rating:{$gt:9}, author:"Jose Vasconcelos" } )
Example of OR operator. Find books with ratong 7 or 10
[Link]( { $or: [ {rating:7}, {rating:10} ] })
A mopre complex filter
[Link]( { $or: [ {rating:{$gt:9} }, { author:"Jose Vasconcelos"
} ] })
In and nin
Find books, where rating value is in [7, 8].
[Link]( { rating:{ $in:[7, 8] } } )
[
{
_id: ObjectId("6413cae75bce717f77e1325b"),
title: 'The color of magic',
author: 'Terry Pratchett',
pages: 300,
rating: 7,
genres: [ 'fantasy', 'magic' ]
},
{
_id: ObjectId("6413cc635bce717f77e1325d"),
title: 'The light fantastics',
author: 'Terry Pratchett',
pages: 250,
rating: 7,
genres: [ 'fantasy' ]
}
]
Find books, where rating value is not in [7, 8, 9].
[Link]( { rating:{ $nin:[7, 8, 9] } } )
[
{
_id: ObjectId("6413cc635bce717f77e1325e"),
title: 'Dune',
author: 'Frank Herbert',
pages: 500,
rating: 10,
genres: [ 'sci-fi', 'magic' ]
},
{
_id: ObjectId("6414649eecd980628b90377a"),
title: 'Mi planta de naranja Lima',
author: 'Jose Vasconcelos',
rating: 10,
pages: 400,
genres: [ 'fantasy' ],
reviews: [
{ name: 'Goku', body: 'Great book :)' },
{ name: 'Vegeta', body: 'Bad' }
]
}
]
Querying arrays
Array attributes could be used in find.
[Link]( { genres:"magic" } )
[
{
_id: ObjectId("6413cae75bce717f77e1325b"),
title: 'The color of magic',
author: 'Terry Pratchett',
pages: 300,
rating: 7,
genres: [ 'fantasy', 'magic' ]
},
{
_id: ObjectId("6413cc635bce717f77e1325e"),
title: 'Dune',
author: 'Frank Herbert',
pages: 500,
rating: 10,
genres: [ 'sci-fi', 'magic' ]
}
]
If we need to get books where genres is exactly [“magic”].
[Link]( { genres:["magic"] } )
All books which have fantasy and magic in genres.
[Link]( { genres:{ $all:["fantasy", "magic"] } } )
[
{
_id: ObjectId("6413cae75bce717f77e1325b"),
title: 'The color of magic',
author: 'Terry Pratchett',
pages: 300,
rating: 7,
genres: [ 'fantasy', 'magic' ]
}
]
Find using nested documents attributes
Books where a reviwer is Mario.
[Link]( { "[[Link]](<[Link] } )
[
{
_id: ObjectId("641462fbecd980628b903779"),
title: 'The Way of Kings',
author: 'Brandom Sanderson',
rating: 9,
pages: 400,
genres: [ 'fantasy' ],
reviews: [
{ name: 'Yoshi', body: 'Great book' },
{ name: 'Mario', body: 'so so' }
]
}
]
Ejercicios
Inserte 3 libros adicionales. Considere incluir dested documents para los reviews.
Muestre los libros que tengan mas de 300 páginas y tengan como genero ‘fantasy’.
Muestre el título de los libros que tengan un rating de 7, 8 o 9.
Muestre el título y autor de los libros que tengan mas de 200 páginas o que el auor sea
Brandom Sanderson.
Muestre una lista de libros ordenados por título, que como revisores (reviews) a
‘Mario’.
Mongo DB part 3
Delete
Firt of all, insert some authors:
[Link]( [ {name:"Vicente", age:50}, {name:"Enrique",
age:100},{name:"Pamela", age:20},{name:"Claudia", age:50}, ] )
{
acknowledged: true,
insertedIds: {
'0': ObjectId("6414944decd980628b90377c"),
'1': ObjectId("6414944decd980628b90377d"),
'2': ObjectId("6414944decd980628b90377e"),
'3': ObjectId("6414944decd980628b90377f")
}
}
Now we could delete
[Link]( { _id:ObjectId("6414944decd980628b90377c") } )
Delete many authors, where age is greater than 50
[Link]( { age:{$gt:50} } )
Update
Update a book where id = 6413cae75bce717f77e1325b, and we set pages and rating to
100 and 5 respectively.
[Link]( {_id: ObjectId("6413cae75bce717f77e1325b")}, {
$set:{pages:100, rating:5} } )
Update all books where author is Terry Pratchett.
[Link]( {author:"Terry Pratchett"} , {$set:{
author:"Terry Pratchet" }} )
Increase plus two, the number of pages of a book.
[Link]( { _id: ObjectId("6413cae75bce717f77e1325b") }, {
$inc:{pages:2} } )
Update the genres array attribute, deleting the “fantasy” element
[Link]( {_id: ObjectId("6413cae75bce717f77e1325b")}, {
$pull:{ genres:"fantasy" } } )
Update the genres array attribute, pushing the “fantasy” element
[Link]( {_id: ObjectId("6413cae75bce717f77e1325b")}, {
$push:{ genres:"fantasy" } } )
Update the genres array attribute, pushing several elements
[Link]( {_id: ObjectId("6413cae75bce717f77e1325b")}, {
$push:{ genres: { $each:[ "thriller", "comedy" ] } } } )
Indexes
Creates an index for attribute rating with value 10
[Link]({rating:10})
To see all indexes
[Link]()
[
{ v: 2, key: { _id: 1 }, name: '*id*' },
{ v: 2, key: { rating: 10 }, name: 'rating_10' }
]
If we perform, it will access jst three documents and not all:
[Link]({rating:10}).explain('executionStats')
...
isEOF: 1,
docsExamined: 3,
alreadyHasObj: 0,
---
Ejercicios
Creen 5 documentos de usuarios que tengan nombre, apellido, edad, telefonos.
Elimine a los usuarios que tengan una edad menor a 10 años.
Actualicen a los usuarios que se llamen como usted, y cambiele de nombre por
Davinchi.
Actualicen al usuario Davinchi y agregele estos números: 1111111, +51323265465, 00-
1151451
// Importa Express y MongoClient
var express = require('express');
var MongoClient = require('mongodb').MongoClient;
// Crea una instancia de Express
var app = express();
[Link]([Link]()); // Habilita el manejo de datos JSON en las solicitudes
var url = 'mongodb://localhost:27017'; // URL de tu base de datos MongoDB
var dbName = 'base_prueba'; // Nombre de tu base de datos
// Define una ruta POST para registrar un usuario
[Link]('/registrar-usuario', async function (req, res) {
try {
// Extrae los datos del cuerpo de la solicitud
var { nombre, email, contraseña, edad } = [Link];
// Conecta con la base de datos
var client = new MongoClient(url, { useUnifiedTopology: true });
await [Link]();
// Accede a la base de datos y la colección de usuarios
var db = [Link](dbName);
var usuarios = [Link]('usuarios');
// Inserta un nuevo documento en la colección de usuarios
var result = await [Link]({ nombre, email, contraseña, edad });
// Cierra la conexión con la base de datos
[Link]();
// Verifica si la inserción fue exitosa y responde con un JSON
if (result && [Link]) {
[Link]({ registrado: true, resultado: result });
} else {
[Link]({ registrado: false, resultado: result });
} catch (error) {
// Maneja cualquier error que ocurra durante el proceso
[Link]('Error al registrar usuario:', error);
[Link]({ registrado: false });
});
var PORT = 8081;
// Inicia el servidor en el puerto especificado
[Link](PORT, function () {
[Link]('Servidor escuchando en el puerto ' + PORT);
});
En JavaScript, las operaciones pueden ser síncronas o asíncronas. Las operaciones síncronas se
ejecutan secuencialmente, una detrás de otra. Las operaciones asíncronas, por otro lado,
permiten que el programa continúe ejecutándose mientras espera que ciertas tareas se
completen en segundo plano.
Las funciones asíncronas son una característica de JavaScript que permite manejar operaciones
asíncronas de una manera más legible y fácil de usar. La palabra clave async se usa para definir
una función como asíncrona. Esta característica permite utilizar await dentro de la función, lo
que hace que JavaScript espere a que las promesas se resuelvan antes de continuar ejecutando
el código.
Veamos un ejemplo para entenderlo mejor:
javascript
Copy code
async function ejemplo() {
// Aquí se realizarán operaciones asíncronas
// Esperaremos que se completen utilizando 'await'
let resultado = await operacionAsincrona(); // Espera a que 'operacionAsincrona' se
complete
// Continúa con el código después de que 'operacionAsincrona' se completa
return resultado;
En este ejemplo, operacionAsincrona es una función que devuelve una promesa. Al usar await
delante de operacionAsincrona(), le decimos a JavaScript que espere hasta que esta operación
asíncrona se complete antes de continuar ejecutando el código dentro de la función ejemplo.
Esto es útil cuando trabajas con operaciones que llevan tiempo, como las solicitudes a una base
de datos o las peticiones a servidores externos. Las funciones asíncronas, junto con await,
permiten escribir código de manera más clara y mantenible al manejar tareas asincrónicas de
una manera más sincrónica.