是否可以像MySQL subselect一样限制扫描文档的数量?

是否可以像MySQL subselect一样限制扫描文档的数量?,mysql,mongodb,mongodb-query,Mysql,Mongodb,Mongodb Query,当查询包含数百万文档的MongoDB集合并对非索引字段进行筛选或排序时,查询运行太慢,因为mongo需要扫描整个集合。在Mysql上,这可以通过执行仅筛选最后40k行的子选择来实现,例如: select c.name, c.age, c.address //another fields from (select * from myTable order by id desc limit 40000) as c where c.name = 'My name' //more and more

当查询包含数百万文档的MongoDB集合并对非索引字段进行筛选或排序时,查询运行太慢,因为mongo需要扫描整个集合。在Mysql上,这可以通过执行仅筛选最后40k行的子选择来实现,例如:

select c.name, c.age, c.address //another fields
  from (select * from myTable order by id desc limit 40000) as c
 where c.name = 'My name' //more and more filters
 order by c.date_req desc
 limit 25
在这个SQL中,我得到最后40k行,然后应用过滤和排序逻辑,即使表中有数百万行,它也能快速运行


在MongoDB上,我只有在过滤或排序索引字段时才能获得良好的性能,否则,它运行得太慢。我假设我不能在每个字段中创建索引,那么在这种情况下我能做什么呢?MongoDB上也有类似的情况吗?

您可以通过使用聚合管道来实现这一点,聚合管道按照您需要的顺序执行操作:

db.coll.aggregate([
    // Get the last 40k docs
    {$sort: {_id: -1}},
    {$limit: 40000},
    // Filter and sort those docs
    {$match: {name: 'My name'}},
    {$sort: {date_req: -1}},
    // Take the first 25 of those
    {$limit: 25}
])

这看起来很有趣。。我今天会测试它,并给你一个反馈。谢谢:D