MongoDB Aggregation Pipeline for Filtering, Grouping, and Sorting

  • Share this:

Code introduction


This function uses MongoDB's aggregation pipeline to process data in the collection. It first uses the $match stage to filter records, then uses the $group stage to group records and calculate the sum of values for each category, and finally uses the $sort stage to sort by the sum.


Technology Stack : pymongo

Code Type : The type of code

Code Difficulty : Intermediate


                
                    
def aggregate_filter_sort(arg1, arg2):
    # Connect to the MongoDB client
    client = pymongo.MongoClient("mongodb://localhost:27017/")
    db = client["test_database"]
    collection = db["test_collection"]

    # Perform an aggregation with a filter, a group, and a sort
    pipeline = [
        {"$match": arg1},
        {"$group": {"_id": "$category", "total": {"$sum": "$value"}}},
        {"$sort": {"total": -1}}
    ]

    # Execute the aggregation pipeline
    results = collection.aggregate(pipeline)

    # Return the results
    return list(results)                
              
Tags: