Note that there are some explanatory texts on larger screens.

plurals
  1. POSlow (high latency) upon queries with sort mongoDB
    primarykey
    data
    text
    <p>I am currently migrating from couchdb to mongodb, still learning this stuff and have a problem anytime I do some queries with sorting in my webpage. I am using codeigniter as the framework and using <a href="https://github.com/alexbilbie/codeigniter-mongodb-library/tree/v2" rel="nofollow">alexbilbie</a> lib for mongodb php library.</p> <p>So, here is my problem: I intend to do queries from sensors in a room that updated each second (thus, already saved thousands docs in collection) and to get each latest sensor value I use this query from model:</p> <pre><code>function mongoGetDocLatestDoc($sensorid){ $doc = $this-&gt;mongo_db-&gt;where(array('SensorId'=&gt;$sensorid))-&gt;limit(1)-&gt;order_by(array('_id'=&gt;'DESC'))-&gt;get('my_mongo'); return $doc; } </code></pre> <p>if I called this with my controller, it took a lot of time to process the query and even worse if I change the sort by timestamp. and it is double the latency each time I called this again for the second sensor, let alone I have more than 10 sensors that need this query in the same page. Am I doing it wrong or there is some more efficient way to get the latest data from collection?</p> <p>edit: @Sammaye : I tried making an index based on your suggestion and here is the explain generated after I executed the query:</p> <pre><code>"cursor" : "BtreeCursor timestamp_desc", "nscanned" : 326678, "nscannedObjects" : 326678, "n" : 50, "millis" : 4402, "nYields" : 7, "nChunkSkips" : 0, "isMultiKey" : false, "indexOnly" : false, "indexBounds" : { "timestamp" : [ [ { "$maxElement" : 1 }, { "$minElement" : 1 } ] ] } </code></pre> <p>as per comparison, this explain the first query without using index (that executed faster) :</p> <pre><code>"cursor" : "BasicCursor", "nscanned" : 385517, "nscannedObjects" : 385517, "n" : 50, "millis" : 1138, "nYields" : 0, "nChunkSkips" : 0, "isMultiKey" : false, "indexOnly" : false, "indexBounds" : { } </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.
 

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