MongoDb: Search value in ranges in different situations -



MongoDb: Search value in ranges in different situations -

first.

we have follows records in db

{ _id:1, values: [ 1 ,5 ,6 ,8]}, { _id:2, values: [5 ,7 ,8,10 ,40 ,1]}, { _id:3, values: [50 ,60 ,5 ,1 ]}

i need query records whitch consist 'values' range 8 - 10. result must {_id:1},{_id:2}

query ({values:{'$gte':8,'$lte':10}}) homecoming records , not right result, due 'values' array!!

second.

we have follows records in db

{_id:1, from: 1, to:100}, {_id:2, from: 101, to:200}, {_id:3, from: 201, to:300}, {_id:4, from: 301, to:400} ...

i need found records element 205 within range from-to . result {_id:3}

query({from:{'$lte':205},to:{'$gte':205})

is slow , dont utilize indexes {from:1,to:1} @ all;

i'm bit confused. can help, please.

thank you.

case 1: range query on array values

edit: did test using wrong values.

as documentation explains, using conditional operators on array values (and implicit operator), needs match 1 status homecoming document.

so,

_id:1 matches $lte , $gte clauses: ok _id:2 matches $lte , $gte clauses: ok _id:3 matches $lte (5 < 10 , 1 < 10) clause: not ok works intended documentation explains.

if need filter using range queries on array values have wrap values using objects, follows:

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}]}

if want utilize index query, can follows:

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, ... } case 2: hitting index using open ranges

as can see query hits index expected.

for(var i=0 ; i<120000 ; i++) { ... db.test_col.insert({from: (math.random()*100)%100, to: (math.random()*100)%100}); ... } > db.test_col.ensureindex({from:1, to:1}) > db.test_col.count() 120002 > 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" }

mongodb

Comments

Popular posts from this blog

web services - java.lang.NoClassDefFoundError: Could not initialize class net.sf.cglib.proxy.Enhancer -

Accessing MATLAB's unicode strings from C -

javascript - mongodb won't find my schema method in nested container -