Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <h2>Case 1: Range query over array values</h2> <p>EDIT: i did the test using wrong values.</p> <p>As <a href="http://docs.mongodb.org/manual/reference/operators/#array" rel="nofollow">documentation explains</a>, using conditional operators over array values (AND implicit operator), only needs to match one condition to return the document.</p> <p>So, </p> <ul> <li>_id:1 matches $lte and $gte clauses: <strong>OK</strong></li> <li>_id:2 matches $lte and $gte clauses: <strong>OK</strong></li> <li>_id:3 matches only $lte (5 &lt; 10 and 1 &lt; 10) clause: <strong>NOT OK</strong> but works as intended as the documentation explains.</li> </ul> <p>If you need to filter using this range queries over the array values you have to wrap the values using objects, as follows:</p> <pre><code>db.test_col2.insert({values:[{v:1} ,{v:5 },{v:6} ,{v:8}]}) db.test_col2.insert({values:[{v:5 },{v:7} ,{v:8},{v:10 },{v:40} ,{v:1}]}) db.test_col2.insert({values: [{v:50} ,{v:60} ,{v:5} ,{v:1} ]}) db.test_col2.find({values: {$elemMatch:{v:{$lte:10, $gte:8}}} }) {"_id":ObjectId("51273098140d09d9105739b5"),"values":[{"v":1},{"v":5},{"v":6},{"v":8}]} {"_id":ObjectId("51273098140d09d9105739b6"),"values":[{"v":5},{"v":7},{"v":8},{"v":10},{"v":40},{"v":1}]} </code></pre> <p>If you want to use an index for this query, you can do it as follows:</p> <pre><code>db.test_col2.ensureIndex({"values.v":1}) db.test_col2.find({values: {$elemMatch:{v:{$lte:10, $gte:8}}} }).explain() { "cursor": "BtreeCursor values.v_1", "isMultiKey": true, ... } </code></pre> <h2>Case 2: Hitting the index using open ranges</h2> <p>As you can see this query hits the index as expected.</p> <pre><code>for(var i=0 ; i&lt;120000 ; i++) { ... db.test_col.insert({from: (Math.random()*100)%100, to: (Math.random()*100)%100}); ... } &gt; db.test_col.ensureIndex({from:1, to:1}) &gt; db.test_col.count() 120002 &gt; db.test_col.find({from:{$gte:3}, to:{$lt:60}}).explain() { "cursor" : "BtreeCursor from_1_to_1", "isMultiKey" : false, "n" : 69741, "nscannedObjects" : 69902, "nscanned" : 116563, "scanAndOrder" : false, "indexOnly" : false, "nYields" : 0, "nChunkSkips" : 0, "millis" : 340, "indexBounds" : { "from" : [ [ 3, 1.7976931348623157e+308 ] ], "to" : [ [ -1.7976931348623157e+308, 60 ] ] }, "server" : "new-host-2.home:27017" } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload