Skip to content

Add _meta to aggregation results (via $facet support) #1208

Description

@Wytamma

I think _perform_aggregation could be modified with $facet to return a count value with the aggregation results. I know limitaions says that it's not the intended behaviour, however, I think it would be beneficial.

Here's how I would consider implementing:

def _perform_aggregation(resource, pipeline, options):
    ...
    paginated_results = []
    if req.max_results > 1:
        limit = {"$limit": req.max_results}
        skip = {"$skip": (req.page - 1) * req.max_results}
        paginated_results.append(skip)
        paginated_results.append(limit)
    else:
        # sub-pipeline in $facet stage cannot be empty
        skip = {"$skip": 0}
        paginated_results.append(skip)
    
    facet_pipelines = {}
    facet_pipelines["paginated_results"] = paginated_results
    facet_pipelines["total_count"] = [{"$count": "count"}]

    facet = {"$facet":facet_pipelines}

    req_pipeline.append(facet)

    getattr(app, "before_aggregation")(resource, req_pipeline)

    cursor = app.data.aggregate(resource, req_pipeline, options).next()

    for document in cursor['paginated_results']:
        documents.append(document)

    getattr(app, "after_aggregation")(resource, documents)

    response[config.ITEMS] = documents

    # add pagination info
    if config.DOMAIN[resource]["pagination"]:
        count = cursor['total_count'][0]['count']
        response[config.META] = _meta_links(req, count)

    return response, None, None, 200, []

This modification would change the aggregate pipeline considerably, so maybe a config variable could be used to control this behaviour for those already hooking into "before_aggregation".

Am I missing anything obvious? Should I try implementing this and submitting a PR?

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions