user2846870
user2846870

Reputation: 581

Mongo Aggregate not using Index

My mongo find query is using an index, but the same functionality if I am implementing using aggregate, it is not using the Index.

db.collection1.find({Attribute8: "s1000",Attribute9: "s1000"}).sort({Attribute10: 1})

"cursor used in find" : "BtreeCursor Attribute8_1_Attribute9_1_Attribute10_1"

 db.collection1.aggregate([
      {
        $match: {
          Attribute8: "s1000",
          Attribute9: "s1000"
        }
      },
      {
        $sort: {
         Attribute10: 1
        }
      }
    ])

"cursor used in aggregate" : "BtreeCursor ".

Can someone tell me where it went wrong. My goal is to use Indexes in aggregate method. Thanks in advance.

Upvotes: 3

Views: 2509

Answers (1)

Kevin
Kevin

Reputation: 516

After some digging the issue is the limitation of usage of the following types:

Symbol, MinKey, MaxKey, DBRef, Code, and CodeWScope

In this case Symbol is used for containing a string value, so index wont work.

Please try with a Number en set explain to true in the aggregate option.


[EDIT] My previous answer is incorrect.

The aggregation pipeline is using a 'BtreeCursor' (only when the defined field has an index) to run the $match query and does uses the ensured index, check "indexBound" for verification.

Ensuring the whole collection to have an index on "Attribute08"


    db.temps.ensureIndex({Attribute08:1})

$match on a field with an index:


    db.temps.aggregate([{$match:{Attribute08:"s1000"}}],{explain:true})

    "allPlans" : [
             {
                     "cursor" : "BtreeCursor ",
                     "isMultiKey" : false,
                     "scanAndOrder" : false,
                     "indexBounds" : {
                             "Attribute08" : [
                                     [
                                             "s1000",
                                             "s1000"
                                     ]
                             ]
                     }
             }
     ]

Below the $match on a field without index:


    db.temps.aggregate([{$match:{Attribute09:"s1000"}}],{explain:true})
    "allPlans" : [
            {
                    "cursor" : "BasicCursor",
                    "isMultiKey" : false,
                    "scanAndOrder" : false
            }
    ]

Upvotes: 1

Related Questions