简体   繁体   English

如何在MongoDB中选择一个字段大于其他字段的文档?

[英]How to select documents with one field greater than other in MongoDB?

I have mongodb documents like this 我有像这样的mongodb文件

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

How to select documents with field "from" greater than "to" in MongoDB? 如何在MongoDB中选择字段“from”大于“to”的文档? I tried something like this but it doesn't work at all. 我试过这样的东西,但根本不起作用。

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

I would recommend against using $where . 我建议不要使用$where It will be slow at scale. 它的规模会很慢。

For this use case, you will want to move your logic from your query to your document schema. 对于此用例,您需要将逻辑从查询移动到文档架构。 Add a new attribute to your document called "from_to_diff" and set it to "from" - "to" at document write time. 在文档中添加一个名为“from_to_diff”的新属性,并在文档写入时将其设置为“from” - “to”。

Then, run the following query: 然后,运行以下查询:

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

Then, create an index on {from_to_diff: 1}. 然后,在{from_to_diff:1}上创建索引。 You will have good cardinality on your index, and not run the massive table scans you will have with $where . 你的索引上会有很好的基数,而不会运行你在$where的大量表扫描。

它应该是这样的;)

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM