【问题标题】:How to select documents with one field greater than other in MongoDB?如何在 MongoDB 中选择一个字段大于其他字段的文档?
【发布时间】:2013-08-21 15:19:36
【问题描述】:

我有这样的 mongodb 文档

[_id] => MongoId Object (
    [$id] => 52135a6baabacb9f948b4567
)
[change] => 7
[from] => 8
[to] => 1

如何在 MongoDB 中选择字段“from”大于“to”的文档?我尝试了类似的方法,但它根本不起作用。

$collection->find( array('from' => array('$gt' => 'to') ) );

【问题讨论】:

    标签: php mongodb


    【解决方案1】:

    我建议不要使用$where。规模化会很慢。

    对于这个用例,您需要将您的逻辑从您的查询移到您的文档架构中。为您的文档添加一个名为“from_to_diff”的新属性,并在文档写入时将其设置为“from”-“to”。

    然后,运行以下查询:

    $collection->find(array('from' => array('$gt' => 0)))

    然后,在 {from_to_diff: 1} 上创建一个索引。您的索引将具有良好的基数,并且不会运行使用 $where 进行的大量表扫描。

    【讨论】:

      【解决方案2】:

      应该是这样的;)

      $collection->find( array('$where' => 'this.from > this.to'  ) );
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-01-07
        • 1970-01-01
        • 1970-01-01
        • 2023-02-11
        • 1970-01-01
        • 2014-08-17
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多