[英]How to select documents with one field greater than other in MongoDB?
我有像这样的mongodb文件
[_id] => MongoId Object (
[$id] => 52135a6baabacb9f948b4567
)
[change] => 7
[from] => 8
[to] => 1
如何在MongoDB中选择字段“from”大于“to”的文档? 我试过这样的东西,但根本不起作用。
$collection->find( array('from' => array('$gt' => 'to') ) );
我建议不要使用$where
。 它的规模会很慢。
对于此用例,您需要将逻辑从查询移动到文档架构。 在文档中添加一个名为“from_to_diff”的新属性,并在文档写入时将其设置为“from” - “to”。
然后,运行以下查询:
$collection->find(array('from' => array('$gt' => 0)))
然后,在{from_to_diff:1}上创建索引。 你的索引上会有很好的基数,而不会运行你在$where
的大量表扫描。
它应该是这样的;)
$collection->find( array('$where' => 'this.from > this.to' ) );
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.