使用 pymongo 过滤数据 find v.s where

Using pymongo filter data find v.s where

我想使用 pymongo 过滤数据。但我不知道这两种方法有何不同。结果显示第一种方法的性能优于第二种方法。但是我已经在我的存储中过滤了一个查询集列表。这是 mongodb 功能吗?或 pymongo 功能?

以下是我的案例:

  1. 使用查找方法:(更快)

    result = pymongo.db.mycollection.find({
       condition1,
       condition2
    })
    
  2. 使用find方法&where表达式:(较慢)

    query_data = pymongo.db.mycollection.find({
       condition1
    })
    
    result = query_data.where(Code("function() {
      return condition2}"))
    

在官方文档中,提到 if 可以使用标准运算符避免使用 $where 表达式。Doc.

基本上你自己已经给出了答案。第一个版本应该是您的首选,因为第二个版本使用 $where 会导致执行时间变慢。原因之一是例如$where 不会使用任何索引 (link)。

您可以在服务器日志中看到 PHP 驱动程序真正发送到 MongoDB 的查询,方法是像这样在服务器上启用日志记录:

db.setLogLevel(1)

此外,一旦您知道了精确的查询,您就可以使用 .explain() 来比较不同的执行计划。