File size: 1,940 Bytes
c58df45
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
from .database_init import get_mongodb
import logging

logger = logging.getLogger(__name__)

def get_collection(collection_name):
    db = get_mongodb()
    return db[collection_name]

def insert_document(collection_name, document):
    collection = get_collection(collection_name)
    try:
        result = collection.insert_one(document)
        logger.info(f"Documento insertado en {collection_name} con ID: {result.inserted_id}")
        return result.inserted_id
    except Exception as e:
        logger.error(f"Error al insertar documento en {collection_name}: {str(e)}")
        return None

def find_documents(collection_name, query, sort=None, limit=None):
    collection = get_collection(collection_name)
    try:
        cursor = collection.find(query)
        if sort:
            cursor = cursor.sort(sort)
        if limit:
            cursor = cursor.limit(limit)
        return list(cursor)
    except Exception as e:
        logger.error(f"Error al buscar documentos en {collection_name}: {str(e)}")
        return []

def update_document(collection_name, query, update):
    collection = get_collection(collection_name)
    try:
        result = collection.update_one(query, update)
        logger.info(f"Documento actualizado en {collection_name}: {result.modified_count} modificado(s)")
        return result.modified_count
    except Exception as e:
        logger.error(f"Error al actualizar documento en {collection_name}: {str(e)}")
        return 0

def delete_document(collection_name, query):
    collection = get_collection(collection_name)
    try:
        result = collection.delete_one(query)
        logger.info(f"Documento eliminado de {collection_name}: {result.deleted_count} eliminado(s)")
        return result.deleted_count
    except Exception as e:
        logger.error(f"Error al eliminar documento de {collection_name}: {str(e)}")
        return 0