"""Controller for entity-related operations.""" from models.database import entity_collection def retrieve_hot_entity(): """Retrieves the top 200 unique entities from a MongoDB collection, sorted by the total occurrence field in descending order. The function returns a dict containing the count of documents and a list of documents. Returns: dict: Contains: - Count (int): The number of unique entities retrieved (up to 200). - Items (list): A list of dictionaries, each containing: - entity: The value of the entity field. - entityType: The value of the entityType field. - total_occurrence: The summed value of the occurrence field for the entity. """ pipeline = [ { "$group": { "_id": { "entity": "$entity", "entityType": "$entityType" }, "total_occurrence": {"$sum": "$occurrence"} } }, { "$project": { "_id": 0, "entity": "$_id.entity", "entityType": "$_id.entityType", "total_occurrence": 1 } }, {"$sort": {"total_occurrence": -1}}, {"$limit": 200} ] result = list(entity_collection.aggregate(pipeline)) res = { "Count": len(result), "Items": result } return res