V
V
Voenniy2013-10-23 15:45:40
MongoDB
Voenniy, 2013-10-23 15:45:40

Mongodb: SORT vs $ORDERBY

I can't figure out what they want from me.
docs.mongodb.org/manual/reference/operator/meta/orderby/

It seems like it's all the same, however, in one case the index is used and 1 record is scanned, in the other case the index is not used and all records in the collection are scanned:

db.user_event_collection.find().sort({created_at:-1}).limit(1).explain()
{
        "cursor" : "BtreeCursor created_at_1 reverse",
        "isMultiKey" : false,
        "n" : 1,
        "nscannedObjects" : 1,
        "nscanned" : 1,
        "nscannedObjectsAllPlans" : 1,
        "nscannedAllPlans" : 1,
        "scanAndOrder" : false,
        "indexOnly" : false,
        "nYields" : 0,
        "nChunkSkips" : 0,
        "millis" : 0,
        "indexBounds" : {
                "created_at" : [
                        [
                                {
                                        "$maxElement" : 1
                                },
                                {
                                        "$minElement" : 1
                                }
                        ]
                ]
        },
        "server" : "devel.local:27017"
}


db.user_event_collection.find({$query:{}, $orderby:{created_at:-1}}).limit(1).explain()
{
        "cursor" : "BasicCursor",
        "isMultiKey" : false,
        "n" : 0,
        "nscannedObjects" : 14723972,
        "nscanned" : 14723972,
        "nscannedObjectsAllPlans" : 14723972,
        "nscannedAllPlans" : 14723972,
        "scanAndOrder" : false,
        "indexOnly" : false,
        "nYields" : 10,
        "nChunkSkips" : 0,
        "millis" : 7846,
        "indexBounds" : {

        },
        "server" : "devel.local:27017"
}


Why is that?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Keith, 2013-10-23
@Voenniy

Because you interfere with the query and the cursor in the second option, and you can’t do that.

db
  .user_event_collection
  .find({
    $query:{},
    $orderby:{created_at:-1},
    $limit: 1,
    $explain: true
  }, onComplete);
  
function onComplete(err, cursor){
  
  cursor.explain(onExplain);
}

function onExplain(error, plan) {
  
  console.log(plan);
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question