Add exercises 27

Signed-off-by: Manuel Vergara <manuel@vergaracarmona.es>
This commit is contained in:
Manuel Vergara 2023-10-10 00:05:16 +02:00
parent 6fb5471334
commit a0d26af9ed
9 changed files with 393 additions and 0 deletions

View File

@ -0,0 +1,29 @@
"""
Conection
"""
from pymongo.mongo_client import MongoClient
from pymongo.server_api import ServerApi
import os
from dotenv import load_dotenv
load_dotenv()
# variables .env
mongopass = os.getenv('mongopass')
mongouser = os.getenv('mongouser')
mongoname = os.getenv('mongoname')
uri = "mongodb+srv://" + \
mongouser + ":" + \
mongopass + "@" + \
mongoname + ".m697hfm.mongodb.net/?retryWrites=true&w=majority"
# Create a new client and connect to the server
client = MongoClient(uri, server_api=ServerApi('1'))
# Send a ping to confirm a successful connection
try:
client.admin.command('ping')
print("Se envió un ping a su deploy. ¡Se ha conectado correctamente a MongoDB!")
except Exception as e:
print(e)

View File

@ -0,0 +1,30 @@
"""
Conectar la aplicación flask a la base de datos MongoDB
"""
from pymongo.mongo_client import MongoClient
from pymongo.server_api import ServerApi
from flask import Flask, render_template
import os
from dotenv import load_dotenv
load_dotenv()
# variables .env
mongopass = os.getenv('mongopass')
mongouser = os.getenv('mongouser')
mongoname = os.getenv('mongoname')
uri = "mongodb+srv://" + \
mongouser + ":" + \
mongopass + "@" + \
mongoname + ".m697hfm.mongodb.net/?retryWrites=true&w=majority"
client = MongoClient(uri, server_api=ServerApi('1'))
print(client.list_database_names())
app = Flask(__name__)
if __name__ == '__main__':
port = int(os.environ.get("PORT", 5000))
app.run(debug=True, host='0.0.0.0', port=port)

View File

@ -0,0 +1,40 @@
"""
Crear una base de datos y una colección
"""
from pymongo.mongo_client import MongoClient
from pymongo.server_api import ServerApi
from flask import Flask, render_template
import os
from dotenv import load_dotenv
load_dotenv()
# variables .env
mongopass = os.getenv('mongopass')
mongouser = os.getenv('mongouser')
mongoname = os.getenv('mongoname')
uri = "mongodb+srv://" + \
mongouser + ":" + \
mongopass + "@" + \
mongoname + ".m697hfm.mongodb.net/?retryWrites=true&w=majority"
client = MongoClient(uri, server_api=ServerApi('1'))
# Creating database
db = client.pruebas_mongodb
# Creating students collection and inserting a document
db.students.insert_one({
'name': 'manuel',
'country': 'Angola',
'city': 'Soria',
'age': 40
})
print(client.list_database_names())
app = Flask(__name__)
if __name__ == '__main__':
port = int(os.environ.get("PORT", 5000))
app.run(debug=True, host='0.0.0.0', port=port)

View File

@ -0,0 +1,41 @@
"""
Insertar varios documentos en una colección
"""
from pymongo.mongo_client import MongoClient
from pymongo.server_api import ServerApi
from flask import Flask, render_template
import os
from dotenv import load_dotenv
load_dotenv()
# variables .env
mongopass = os.getenv('mongopass')
mongouser = os.getenv('mongouser')
mongoname = os.getenv('mongoname')
uri = "mongodb+srv://" + \
mongouser + ":" + \
mongopass + "@" + \
mongoname + ".m697hfm.mongodb.net/?retryWrites=true&w=majority"
client = MongoClient(uri, server_api=ServerApi('1'))
db = client.pruebas_mongodb
students = [
{'name': 'David', 'country': 'UK', 'city': 'London', 'age': 34},
{'name': 'John', 'country': 'Sweden', 'city': 'Stockholm', 'age': 28},
{'name': 'Sami', 'country': 'Finland', 'city': 'Helsinki', 'age': 25},
]
for student in students:
db.students.insert_one(student)
app = Flask(__name__)
if __name__ == '__main__':
# for deployment we use the environ
# to make it work for both production and development
port = int(os.environ.get("PORT", 5000))
app.run(debug=True, host='0.0.0.0', port=port)

View File

@ -0,0 +1,55 @@
"""
Buscar en la base de datos
"""
from pymongo.mongo_client import MongoClient
from pymongo.server_api import ServerApi
from flask import Flask, render_template
import os
from dotenv import load_dotenv
from bson.objectid import ObjectId
load_dotenv()
# variables .env
mongopass = os.getenv('mongopass')
mongouser = os.getenv('mongouser')
mongoname = os.getenv('mongoname')
uri = "mongodb+srv://" + \
mongouser + ":" + \
mongopass + "@" + \
mongoname + ".m697hfm.mongodb.net/?retryWrites=true&w=majority"
client = MongoClient(uri, server_api=ServerApi('1'))
db = client.pruebas_mongodb
student = db.students.find_one({'name': 'David'})
print(student)
print("-"*30)
student_two = db.students.find_one(
{'_id': ObjectId('652472bfccdbb81a3f7473e5')})
print(student_two)
print("-"*30)
students = db.students.find()
for student in students:
print(student)
print("-"*30)
students = db.students.find({}, {"_id": 0, "name": 1, "country": 1})
for student in students:
print(student)
print("-"*30)
app = Flask(__name__)
if __name__ == '__main__':
# for deployment we use the environ
# to make it work for both production and development
port = int(os.environ.get("PORT", 5000))
app.run(debug=True, host='0.0.0.0', port=port)

View File

@ -0,0 +1,70 @@
"""
Buscar en la base de datos con query
"""
from pymongo.mongo_client import MongoClient
from pymongo.server_api import ServerApi
from flask import Flask, render_template
import os
from dotenv import load_dotenv
from bson.objectid import ObjectId
load_dotenv()
# variables .env
mongopass = os.getenv('mongopass')
mongouser = os.getenv('mongouser')
mongoname = os.getenv('mongoname')
uri = "mongodb+srv://" + \
mongouser + ":" + \
mongopass + "@" + \
mongoname + ".m697hfm.mongodb.net/?retryWrites=true&w=majority"
client = MongoClient(uri, server_api=ServerApi('1'))
db = client.pruebas_mongodb
query = {
"country": "Finland"
}
students = db.students.find(query)
for student in students:
print(student)
print("-"*30)
query = {
"city": "Helsinki"
}
students = db.students.find(query)
for student in students:
print(student)
print("-"*30)
query = {
"country": "Finland",
"city": "Helsinki"
}
students = db.students.find(query)
for student in students:
print(student)
print("-"*30)
query = {"age": {"$gt": 30}}
students = db.students.find(query)
for student in students:
print(student)
app = Flask(__name__)
if __name__ == '__main__':
# for deployment we use the environ
# to make it work for both production and development
port = int(os.environ.get("PORT", 5000))
app.run(debug=True, host='0.0.0.0', port=port)

View File

@ -0,0 +1,71 @@
"""
Buscar en la base de datos - más opciones
"""
from pymongo.mongo_client import MongoClient
from pymongo.server_api import ServerApi
from flask import Flask, render_template
import os
from dotenv import load_dotenv
from bson.objectid import ObjectId
load_dotenv()
# variables .env
mongopass = os.getenv('mongopass')
mongouser = os.getenv('mongouser')
mongoname = os.getenv('mongoname')
uri = "mongodb+srv://" + \
mongouser + ":" + \
mongopass + "@" + \
mongoname + ".m697hfm.mongodb.net/?retryWrites=true&w=majority"
client = MongoClient(uri, server_api=ServerApi('1'))
db = client.pruebas_mongodb
db.students.find().limit(3)
print("-"*30)
students = db.students.find().sort('name')
for student in students:
print(student)
print("-"*30)
students = db.students.find().sort('name', -1)
for student in students:
print(student)
print("-"*30)
students = db.students.find().sort('age')
for student in students:
print(student)
print("-"*30)
students = db.students.find().sort('age', -1)
for student in students:
print(student)
print("-"*30)
# New value
query = {'age': 40}
new_value = {'$set': {'age': 38}}
db.students.update_one(query, new_value)
# lets check the result if the age is modified
for student in db.students.find():
print(student)
app = Flask(__name__)
if __name__ == '__main__':
# for deployment we use the environ
# to make it work for both production and development
port = int(os.environ.get("PORT", 5000))
app.run(debug=True, host='0.0.0.0', port=port)

View File

@ -0,0 +1,46 @@
"""
Buscar en la base de datos con query
"""
from pymongo.mongo_client import MongoClient
from pymongo.server_api import ServerApi
from flask import Flask, render_template
import os
from dotenv import load_dotenv
from bson.objectid import ObjectId
load_dotenv()
# variables .env
mongopass = os.getenv('mongopass')
mongouser = os.getenv('mongouser')
mongoname = os.getenv('mongoname')
uri = "mongodb+srv://" + \
mongouser + ":" + \
mongopass + "@" + \
mongoname + ".m697hfm.mongodb.net/?retryWrites=true&w=majority"
client = MongoClient(uri, server_api=ServerApi('1'))
db = client.pruebas_mongodb
# Delete one document
query = {'name': 'John'}
db.students.delete_one(query)
# Delete many documents
for student in db.students.find():
print(student)
for student in db.students.find():
print(student)
# Drop collection
db.students.drop()
app = Flask(__name__)
if __name__ == '__main__':
# for deployment we use the environ
# to make it work for both production and development
port = int(os.environ.get("PORT", 5000))
app.run(debug=True, host='0.0.0.0', port=port)

View File

@ -6,4 +6,15 @@ Documento original en inglés: [Python with MondoDB](https://github.com/Asabeneh
Repasar [ejemplos](https://github.com/Asabeneh/30-Days-Of-Python/blob/master/27_Day_Python_with_mongodb/27_python_with_mongodb.md) Repasar [ejemplos](https://github.com/Asabeneh/30-Days-Of-Python/blob/master/27_Day_Python_with_mongodb/27_python_with_mongodb.md)
### Solución
[01_proof_conection_mongo.py](01_proof_conection_mongo.py)
[02_connect_flask_app.py](02_connect_flask_app.py)
[03_create_db_collection.py](03_create_db_collection.py)
[04_Insert_many_docs_collection.py](04_Insert_many_docs_collection.py)
[05_find.py](05_find.py)
[06_find_query.py](06_find_query.py)
[07_find_more_opcions.py](07_find_more_opcions.py)
[08_delete_doc.py](08_delete_doc.py)
[<< Day 26](../26_Desarrollo_web_en_Python/README.md) | [Day 28 >>](../28_API/README.md) [<< Day 26](../26_Desarrollo_web_en_Python/README.md) | [Day 28 >>](../28_API/README.md)