mongodb - 聚合框架中的 $skip 和 $limit

当我阅读文档时,我发现了以下注释:

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.

如果我是对的,它只适用于我同时使用 $sort 和 $limit 的情况

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

但是,我认为大多数时候我们都会有

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

问题 1:如果我在这里使用 $skip,是否意味着上述规则不适用?

我问这个问题是因为理论上 MongoDB 仍然可以计算前 n 条记录,并通过仅排序前 n 条记录来提高性能。我没有找到任何关于这个的文件。如果规则不适用,

问题 2:我是否需要将查询更改为以下内容以提高性能?

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

编辑:我认为解释我的用例会使上述问题更有意义。我正在使用 MongoDB 2.6 提供的文本搜索功能来查找产品。我担心如果用户输入一个非常常见的关键字,如“red”,会返回太多结果。因此,我正在寻找更好的方法来生成此结果。

EDIT2:原来上面最后一段代码等于

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

因此,我们始终可以使用此表单来应用 top n 规则。

最佳答案

由于这是我们正在讨论的文本搜索查询,因此最佳形式是这样的:

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

顶部“排序”结果中内存保留的基本原理只能在它自己的“限制”内发挥作用,这对于超出一些合理“页面”数据的任何内容都不是最佳的。

超出内存消耗的合理范围,额外的阶段可能会产生负面影响而不是正面影响。

这些确实是当前形式的 MongoDB 可用的文本搜索功能的实际限制。但对于更详细且需要更高性能的任何内容,就像许多 SQL“全文”解决方案一样,您最好使用外部“专用”文本搜索解决方案。

https://stackoverflow.com/questions/24160037/

相关文章:

mongodb - 如何查询 MongoDB 以测试项目是否存在?

mongodb - 在 MongoDB 中执行搜索/投影时如何重命名字段?

mongodb - 升级mongodb没有效果仍然显示旧版本

node.js - Nodejs 中的 Mongodb 与 Postgres

mongodb - 无法在提供的主机和端口上连接到 MongoDB

mongodb - 在 Meteor 中运行示例的问题

node.js - MongoDB - 错误 : invalid schema, 预期 mongod

node.js - Mongoose - 验证电子邮件语法

mongodb - 如何在 MongoDB shell 中中止正在运行的查询?

mongodb - 如何在 mongodb 配置文件中设置授权?