<jupyter_start><jupyter_text>Código de gerenciamento do DB<jupyter_code>import pymongo
from pymongo import MongoClient
from pprint import pprint
from bson.objectid import ObjectId
from connection_uri import uri
client = MongoClient(uri)
db = client.brodemy<jupyter_output><empty_output><jupyter_text>Checar se o número de aula já está cadastrado no curso<jupyter_code>def check_if_class_number_is_in_course(course_id, class_number):
    match1 = {
        "$match" : {
            "_id" : course_id
        }
    }
    
    unwind = {
        "$unwind" : "$classes" 
    }
    
    project = {
        "$project" : {
            "class_number" : "$classes.number"
        }
    }
    
    match2 = {
        "$match" : {
            "class_number" : class_number
        }
    }
    
    pipeline = [match1, unwind, project, match2]
    return list(db.courses.aggregate(pipeline))
search_course_by_partial_name("mongo")
check_if_class_number_is_in_course(mongo_course_id, 2)
check_if_class_number_is_in_course(mongo_course_id, 4)<jupyter_output><empty_output><jupyter_text>Remover uma aula de um curso<jupyter_code># remove a class from a course by its ID, returns 1 if class is found, if not, 0
def remove_class_from_course(course_id, class_number):
    query = {
        "_id" : course_id
    }
    
    update = {
        "$pull" : {
            "classes" : {
                "number" : class_number
            }
        }
    }
    
    r = db.courses.update_one(query, update)
    return r.modified_count
remove_class_from_course(mongo_course_id, 1)
db.courses.find_one({"name":{"$regex":"mongodb", "$options":"i"}})
mongo_course = db.courses.find_one({"name":"MongoDB Basics"})
pprint(mongo_course)
mongo_course_id = mongo_course['_id']
mongo_course_id
maria = db.users.find_one({"email":"<EMAIL>"})
pprint(maria)
maria_id = maria['_id']
maria_id<jupyter_output><empty_output><jupyter_text>Checar se o usuário é inscrito no curso<jupyter_code>def check_if_user_has_course(user_id, course_id):
    match = {
        "$match" : {
            "_id" : user_id
        }
    }
    
    project = {
        "$project" : {
            "has_course" : {
                "$in" : [
                    course_id, 
                    "$courses"
                ]
            }
        }
    }
    
    match2 = {
        "$match" : {
            "has_course" : True
        }
    }
    
    pipeline = [match, project, match2]
    
    return list(db.users.aggregate(pipeline))
check_if_user_has_course(maria_id, mongo_course_id)<jupyter_output><empty_output><jupyter_text>Buscar curso por regex<jupyter_code>def search_course_by_partial_name(name):
    query = {
        "name" : {
            "$regex" : name,
            "$options" : "i"
        }
    }
    
    return list(db.courses.find(query))
search_course_by_partial_name("python")<jupyter_output><empty_output><jupyter_text>Criar uma categoria<jupyter_code>def create_category(name):
    document = {
        "category" : name,
        "subs" : []
    }
    
    r = db.categories.insert_one(document)
    return r.inserted_id
create_category("Teste")<jupyter_output><empty_output><jupyter_text>Adicionar uma sub-categoria à categoria<jupyter_code>def add_sub_category(category, sub_category):
    if not isinstance(sub_category, str):
        raise TypeError("Sub-category should be a string")
        
    update = {
        "$push" : {
            "subs" : sub_category
        }
    }
    
    r = db.categories.update_one({"category" : category}, update)
    return r.acknowledged
add_sub_category("Software", "Prolog")<jupyter_output><empty_output><jupyter_text>Descobrir a categoria a qual uma sub-categoria pertence<jupyter_code>def get_category_by_sub(sub_name):
    project = {
        "$project" : {
            "category" : 1,
            "has_sub" : {
                "$in" : [
                    sub_name, "$subs"
                ]
            }
        }
    }
    
    match = {
        "$match" : {
            "has_sub" : True
        }
    }
    
    pipeline = [project, match]
    r = list(db.categories.aggregate(pipeline))
    r = [i['category'] for i in r]
    
    if len(r) != 1:
        print("Multiple categories returned true")
    else:
        r = r[0]
        
    return r
get_category_by_sub("Javascript")<jupyter_output><empty_output><jupyter_text>Criar um documento de usuário<jupyter_code>def make_user(name, password, email):
    user = {
        "name" : name,
        "password" : password,
        "email" : email,
        "courses" : []
    }
    
    return user<jupyter_output><empty_output><jupyter_text>Criar um documento de curso<jupyter_code>def make_course(name, description, instructor_id, category, level, requisites = [], image_src = None):
    if not isinstance(requisites, list):
        raise TypeError('requisites should be a list')
    if not isinstance(instructor_id, ObjectId):
        raise TypeError('instructor_id should be an ObjectId')
    if not isinstance(category, dict):
        raise TypeError('category should be a dict')
        
    course = {
        "name" : name, 
        "description" : description,
        "requisites" : requisites,
        "level" : level,
        "image_src" : image_src,
        "instructor_id" : instructor_id,
        "category" : category,
        "classes" : []
    }
    
    return course<jupyter_output><empty_output><jupyter_text>Criar um documento de categoria<jupyter_code>def make_category(category, sub_category):
    category_doc =  { 
        "category" : category,
        "sub_category" : sub_category
    }
    
    return category_doc<jupyter_output><empty_output><jupyter_text>Criar um documento de aula<jupyter_code>def make_class(number, name, description, duration, url):
    aula = {
        "number" : number,
        "name" : name,
        "description" : description,
        "duration" : duration,
        "url" : url
    }
    
    return aula<jupyter_output><empty_output><jupyter_text>Adicionar uma aula ao curso<jupyter_code>def add_class_to_course(course, aula):
    if not isinstance(aula, dict):
        raise TypeError('aula should be a dict')
    if not isinstance(course, ObjectId):
        raise TypeError('course should be the ObjectId of the course')
        
    query = {
        "_id" : course
    }
    
    update = {
        "$push" : {
            "classes" : aula
        }
    }
    
    r = db.courses.update_one(query, update)
    return r.acknowledged
add_class_to_course(mongo_course_id, make_class(3, "arithmetics", "", 10, "endjf389jxe"))<jupyter_output><empty_output><jupyter_text>Adicionar o curso ao usuário<jupyter_code>def add_course_to_user(user, course):
    if not isinstance(course, ObjectId):
        raise TypeError('course should be the ObjectId of the course')
    if not isinstance(user, ObjectId):
        raise TypeError('user should be the ObjectId of the user')
    
    query = {
        "_id" : user
    }
    
    update = {
        "$push" : {
            "courses" : course
        }
    }
    
    r = db.users.update_one(query, update)
    return r.acknowledged<jupyter_output><empty_output><jupyter_text>Adicionar usuário<jupyter_code>def add_user(user):
    if not isinstance(user, dict):
        raise TypeError('user should be a dict')
        
    r = db.users.insert_one(user)
    return r.inserted_id<jupyter_output><empty_output><jupyter_text>Adicionar curso<jupyter_code>def add_course(course):
    if not isinstance(course, dict):
        raise TypeError('course should be a dict')
        
    r = db.courses.insert_one(course)
    return r.inserted_id
add_user(make_user("maria", "jose", "<EMAIL>"))
lucas_id = add_user(make_user("lucas","l1234","<EMAIL>"))
print(lucas_id)
course_id = add_course(make_course("MongoDB Basics", "Introductory MongoDB", lucas_id, 
                                   {"category":"banco de dados", "sub_category":"mongodb"},
                                   "basic"))
pink = make_user("pink", "b123", "<EMAIL>")
pink
pink_id = add_user(pink)
pink_id
course = db.courses.find_one({"name" : "MongoDB Basics"})
course_id = course['_id']
users = list(db.users.find({}, {"_id":1}))
users
for user in users:
    add_course_to_user(user['_id'], mongo_course_id)
get_students_of_course(mongo_course_id)
add_course_to_user(pink_id, course_id)
add_class_to_course(course_id, make_class("Introduction", "Course presentation", 5, 
                                          "https://www.youtube.com/watch?v=9OPP_1eAENg"))
maria = db.users.find_one({"email":"<EMAIL>"})
maria_id = maria['_id']
print(maria_id)
add_course_to_user(maria_id, course_id)
python_course = db.courses.find_one({"name":"Python 101"})
python_course_id = python_course['_id']
python_course_id
add_course_to_user(maria_id, python_course_id)
usr_id = add_user(make_user("Gustavo","12234","<EMAIL>"))
usr_id
add_course_to_user(maria_id, add_course(make_course("Nome teste","Aprenda como ser um mandraque",
                                                  lucas_id, make_category("Software","Python"),
                                                  "Hard",["Python basico"])))<jupyter_output><empty_output><jupyter_text>Visualizando os cursos dos instrutores:<jupyter_code>def see_instructor_courses(instructor = None):
    lookup = {
        "$lookup" : {
            "from" : "courses",
            "localField" : "_id",
            "foreignField" : "instructor_id",
            "as" : "instructor_courses"
        }
    }
    
    project = {
        "$project" : {
            "total_courses" : {
                "$size" : "$instructor_courses"
            },
            "email" : 1,
            "name" : 1,
            "instructor_courses" : 1
        }
    }
    
    if isinstance(instructor, ObjectId):
        match = {
            "$match" : {
                "_id" : instructor
            }
        }
    elif isinstance(instructor, str):
        match = {
            "$match" : {
                "email" : instructor 
            }
        }
    else:
        match = {
            "$match" : {
                "total_courses" : {
                    "$gt" : 0
                }
            }
        }
    
    pipeline = [lookup, project, match]

    return list(db.users.aggregate(pipeline))
pprint(see_instructor_courses())
pprint(see_instructor_courses("<EMAIL>"))
pprint(see_instructor_courses(maria_id))
pprint(see_instructor_courses(lucas_id))<jupyter_output>[{'_id': ObjectId('5b0f392031b3522887252ad1'),
  'email': '<EMAIL>',
  'instructor_courses': [{'_id': ObjectId('5b11693e31b35202d4c8ef5a'),
                          'category': {'category': 'software',
                                       'sub_category': 'python'},
                          'classes': [],
                          'description': 'Introductory Python',
                          'image_src': None,
                          'instructor_id': ObjectId('5b0f392031b3522887252ad1'),
                          'level': 'basic',
                          'name': 'Python 101',
                          'requisites': []},
                         {'_id': ObjectId('5b1169eb31b35202d4c8ef5c'),
                          'category': {'category': 'banco de dados',
                                       'sub_category': 'mongodb'},
                          'classes': [{'description': 'Course presentation',
                                       'duration': 5,
         [...]<jupyter_text>Visualizando os cursos de um aluno:<jupyter_code>def see_user_courses(user = None):
    unwind = {
        "$unwind" : "$courses"
    }
    
    lookup = {
        "$lookup" : {
            "from" : "courses",
            "localField" : "courses",
            "foreignField" : "_id",
            "as" : "course"
        }
    }
    
    project = {
        "$project" : {
            "course" : 1,
            "email" : 1,
            "name" : 1
        }
    }
    
    if isinstance(user, ObjectId):
        match = {
            "$match" : {
                "_id" : user
            }
        }
    elif isinstance(user, str):
        match = {
            "$match" : {
                "email" : user 
            }
        }
    else:
        raise TypeError("user should be either a string or an ObjectId")
    
    pipeline = [unwind, lookup, project, match]

    return list(db.users.aggregate(pipeline))
pprint(see_user_courses("<EMAIL>"))
pprint(list(db.users.find()))
pprint(list(db.courses.find()))<jupyter_output>[{'_id': ObjectId('5b219aa131b3527b09786d8a'),
  'category': {'category': 'banco de dados', 'sub_category': 'mongodb'},
  'classes': [],
  'description': 'Introductory MongoDB',
  'image_src': None,
  'instructor_id': ObjectId('5b219a9f31b3527b09786d89'),
  'level': 'basic',
  'name': 'MongoDB Basics',
  'requisites': []},
 {'_id': ObjectId('5b219b1231b3527b09786d8c'),
  'category': {'category': 'Software', 'sub_category': 'Python'},
  'classes': [],
  'description': 'Aprenda como ser um mandraque',
  'image_src': None,
  'instructor_id': ObjectId('5b219a9f31b3527b09786d89'),
  'level': 'Hard',
  'name': '<NAME>',
  'requisites': ['Python basico']}]<jupyter_text>Visualizar os alunos de um curso<jupyter_code>def get_students_of_course(course_id):
    project = {
        "$project" : {
            "has_course" : {
                "$in" : [
                    course_id, 
                    "$courses"
                ]
            }
        }
    }
    
    match = {
        "$match" : {
            "has_course" : True
        }
    }
    
    pipeline = [project, match]
    
    return list(db.users.aggregate(pipeline))
get_students_of_course(mongo_course_id)<jupyter_output><empty_output><jupyter_text>Remover o curso do aluno<jupyter_code>def remove_course_from_student(course_id, student_id):
    query = {
        "_id" : student_id
    }
    
    update = {
        "$pull" : {
            "courses" : course_id
        }
    }
    
    r = db.users.update_one(query, update)
    return r.modified_count
remove_course_from_student(mongo_course_id, ObjectId('5b1f17af31b3525df1082a63'))
get_students_of_course(mongo_course_id)<jupyter_output><empty_output><jupyter_text>Remover o curso de todos os alunos inscritos<jupyter_code>def remove_course_from_all_students(course_id):
    students = get_students_of_course(course_id)
    students = [i['_id'] for i in students]
    for student in students:
        remove_course_from_student(course_id, student)
        
    print(get_students_of_course(course_id))
remove_course_from_all_students(mongo_course_id)<jupyter_output>[]<jupyter_text>Apagar todos os cursos de um instrutor<jupyter_code>def delete_all_courses_from_instructor(instructor_id):
    courses = see_instructor_courses(instructor_id)
    courses = courses[0]['instructor_courses']
    courses_ids = [i['_id'] for i in courses]
    
    for course_id in courses_ids:
        remove_course_from_all_students(course_id)
        db.courses.delete_one({"_id":course_id})
    
    pprint(see_instructor_courses(instructor_id))
delete_all_courses_from_instructor(ObjectId('5b1f1e2e31b3525df1082a65'))<jupyter_output>[]
[]
[{'_id': ObjectId('5b1f1e2e31b3525df1082a65'),
  'email': '<EMAIL>',
  'instructor_courses': [],
  'name': 'Gustavo',
  'total_courses': 0}]<jupyter_text>Apagar usuário<jupyter_code>def delete_user(user_id):
    delete_all_courses_from_instructor(user_id)
    db.users.delete_one({"_id":user_id})
delete_user(lucas_id)
pprint(list(db.categories.find()))<jupyter_output>[{'_id': ObjectId('5b1eff96cb06673d937bcf75'),
  'category': 'Software',
  'subs': ['C++', 'Java', 'Python', 'Javascript', 'BIRL', 'Prolog']},
 {'_id': ObjectId('5b1f001ecb06673d937bcf77'),
  'category': 'Banco De Dados',
  'subs': ['MySQL', 'PostgreSQL', 'MongoDB']},
 {'_id': ObjectId('5b1f004ecb06673d937bcf78'),
  'category': 'Engenharia',
  'subs': ['Cálculo', 'Física', 'Eletrônica']},
 {'_id': ObjectId('5b1f01f231b3525df1082a61'), 'category': 'Teste', 'subs': []}]<jupyter_text>Listar cursos de uma sub-categoria<jupyter_code>def list_courses_from_sub_category(sub_category):
    return list(db.courses.find({"category.sub_category":{"$regex":sub_category, "$options":"i"}}))
list_courses_from_sub_category("python")<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.1279901356350185, 'fraction_numerical': 0.018557336621454992, 'mean_word_length': 2.6369955156950673, 'pattern_counts': {'":': 15, '<': 103, '<?xml version=': 0, '>': 103, 'https://': 1, 'lorem ipsum': 0, 'www.': 1, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 11, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '24', 'dir': 'jupyter-structured-clean-dedup', 'id': '130651', 'license': 'MIT', 'n_tokens_mistral': 5767, 'n_tokens_neox': 5551, 'n_words': 920, 'path': 'brodemy_db_adm/adm_db.ipynb', 'repo_name': 'FilipeMazzon/brodemy', 'size': '16346'}