Aggregate pipeline with limit and skip

I found on this thread that we can’t use $search with the find method: Looking for a way to use $search fuction via Rest API

and that the aggregation pipeline must be used instead.

Ok but I need to limit and skip because i’m doing a search input in a UI listing.
How would you do that ?

Hey David :wave:

Not sure if this is what you are after but have you tested in the pipeline with $limit and $skip?

As an example similar to the post you linked, using $search and $project only:

curl --location --request POST 'https://data.mongodb-api.com/app/<REDACTED>/endpoint/data/v1/action/aggregate' \
--header 'Content-Type: application/json' \
--header 'Access-Control-Request-Headers: *' \
--header 'api-key: <REDACTED>' \
--data-raw '{
    "collection":"location",
    "database":"myFirstDatabase",
    "dataSource":"Cluster0",
    "pipeline": [
        {
            "$search": {
                "index": "default",
                "range": {
                    "gte": 1,
                    "path": "a"
                }
            }
        }.
        {
            "$project": {"_id": 0}
        }
    ]
}'

Which has a response:

{"documents":[{"a":19},{"a":18},{"a":17},{"a":16},{"a":15},{"a":14},{"a":13},{"a":12},{"a":11},{"a":10},{"a":9},{"a":8},{"a":7},{"a":6},{"a":5},{"a":4},{"a":3},{"a":2},{"a":1}]}%

Using $limit in the pipeline:

curl --location --request POST 'https://data.mongodb-api.com/app/<REDACTED>/endpoint/data/v1/action/aggregate' \
--header 'Content-Type: application/json' \
--header 'Access-Control-Request-Headers: *' \
--header 'api-key: <REDACTED>' \
--data-raw '{
    "collection":"location",
    "database":"myFirstDatabase",
    "dataSource":"Cluster0",
    "pipeline": [
        {
            "$search": {
                "index": "default",
                "range": {
                    "gte": 1,
                    "path": "a"
                }
            }
        },
        {
            "$limit": 3
        },
        {
            "$project": {"_id": 0}
        }
    ]
}'

That gives the following response:

{"documents":[{"a":19},{"a":18},{"a":17}]}%

I’ve not tested with $skip in the above example but you can test it out and let me know if this works for you.

Look forward to hearing from you.

Regards,
Jason

Thanks i will try it, i hope it will work i did not see this in the doc for pipeline.
I’ll let you know.

1 Like

Sounds good, hope it works for you.

Could you link what documentation you were referring to? From the Data API documentation I have taken a look at the pipeline request body states a MongoDB Aggregation Pipeline to be passed through - I’m not sure if there would examples in the docs for each available aggregation stage within Data API context.

I just wanted to clarify in case the docs could be improved.