简体   繁体   中英

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

I have mongodb documents like this

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

How to select documents with field "from" greater than "to" in MongoDB? 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 . 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.

Then, run the following query:

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

Then, create an index on {from_to_diff: 1}. You will have good cardinality on your index, and not run the massive table scans you will have with $where .

它应该是这样的;)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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