$skip and $limit in aggregation framework

白昼怎懂夜的黑 提交于 2020-01-19 04:33:25

问题


When I read the document I found the following notes:

When a $sort immediately precedes a $limit in the pipeline, the $sort operation only maintains the top n results as it progresses, where n is the specified limit, and MongoDB only needs to store n items in memory. This optimization still applies when allowDiskUse is true and the n items exceed the aggregation memory limit.

If I'm right about this, it applies only when I use the $sort and $limit together like

db.coll.aggregate([
    ...,
    {$sort: ...},
    {$limit: limit},
    ...
]);

However, I think most of the time we would have

db.coll.aggregate([
    ...,
    {$sort: ...},
    {$skip: skip},
    {$limit: limit},
    ...
]);

Question 1: Does it mean the rule above doesn't apply if I use $skip here?

I ask this question because theoretically MongoDB can still calculate the top n records and enhance performance by sorting only top n records. I didn't find any document about this though. And if the rule doesn't apply,

Question 2: Do I need to change my query to the following to enhance performance?

db.coll.aggregate([
    ...,
    {$sort: ...},
    {$limit: skip + limit},
    {$skip: skip},
    {$limit: limit},
    ...
]);

EDIT: I think explains my use case would make the question above makes more sense. I'm using the text search feature provided by MongoDB 2.6 to look for products. I'm worried if the user inputs a very common key word like "red", there will be too many results returned. Thus I'm looking for better ways to generate this result.

EDIT2: It turns out that the last code above equals to

db.coll.aggregate([
    ...,
    {$sort: ...},
    {$limit: skip + limit},
    {$skip: skip},
    ...
]);

Thus I we can always use this form to make the top n rule apply.


回答1:


Since this is a text search query we are talking about then the most optimal form is this:

db.collection.aggregate([
    { 
       "$match": {
               "$text": { "$search": "cake tea" }
    }
    },
    { "$sort": { "score": { "$meta": "textScore" } } },
    { "$limit": skip + limit },
    { "$skip": skip }
])

The rationale on the memory reserve from the top "sort" results will only work within it's own "limits" as it were and this will not be optimal for anything beyond a few reasonable "pages" of data.

Beyond what is reasonable for memory consumption, the additional stage will likely have a negative effect rather than positive.

These really are the practical limitations of the text search capabilities available to MongoDB in the current form. But for anything more detailed and requiring more performance, then just as is the case with many SQL "full text" solutions, you are better off using an external "purpose built" text search solution.



来源:https://stackoverflow.com/questions/24160037/skip-and-limit-in-aggregation-framework

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!