关于mongodb:是否有可能像MySQL subselect一样限制扫描文档的数量?

Is it possible to limit the number of scanned documents, similar to MySQL subselect?

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

1
2
3
4
5
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上有与此类似的东西吗?


您可以通过使用按照所需顺序执行操作的聚合管道来执行此操作:

1
2
3
4
5
6
7
8
9
10
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}
])