I have a query built around a composite index, and I've verified from the mongo shell that this query can run as an index only query.
Output:
db.merchants.find({st:{"$regex" : "cr", "$options": "i"}}, {n:1, _id:1})
{ "n" : "Crab shack", "_id" : ObjectId("51c908cc1925f3ca51000001") }
{ "n" : "Tacos R Us", "_id" : ObjectId("51c16f201925f3df4300001b") }
db.merchants.find({st:{"$regex" : "cr", "$options": "i"}}, {n:1, _id:1}).explain()
{
"cursor" : "BtreeCursor st_1_n_1__id_1 multi",
"isMultiKey" : false,
"n" : 2,
"nscannedObjects" : 2,
"nscanned" : 2,
"nscannedObjectsAllPlans" : 2,
"nscannedAllPlans" : 2,
"scanAndOrder" : false,
"indexOnly" : true,
"nYields" : 0,
"nChunkSkips" : 0,
"millis" : 0,
"indexBounds" : {
"st" : [
[
"",
{
}
],
[
/cr/i,
/cr/i
]
],
"n" : [
[
{
"$minElement" : 1
},
{
"$maxElement" : 1
}
]
],
"_id" : [
[
{
"$minElement" : 1
},
{
"$maxElement" : 1
}
]
]
},
"server" : "MacBook-Pro.local:27017"
}
But the same query run from the rails console using mongoid gives me:
Merchant.where({:st => { '$regex'=> "cr", '$options' => 'i' } }).only(:_id, :n).explain
=> {
"cursor"=>"BtreeCursor st_1_n_1__id_1 multi",
"isMultiKey"=>false,
"n"=>2,
"nscannedObjects"=>2,
"nscanned"=>2,
"nscannedObjectsAllPlans"=>2,
"nscannedAllPlans"=>2,
"scanAndOrder"=>false,
"indexOnly"=>false,
"nYields"=>0,
"nChunkSkips"=>0,
"millis"=>0,
"indexBounds"=>{
"st"=>[["", {}], [/cr/i, /cr/i]],
"n"=>[[{"$minElement"=>1}, {"$maxElement"=>1}]], "_id"=>[[{"$minElement"=>1}, {"$maxElement"=>1}]]
},
"allPlans"=>[{"cursor"=>"BtreeCursor st_1_n_1__id_1 multi", "n"=>2, "nscannedObjects"=>2, "nscanned"=>2, "index
Bounds"=>{"st"=>[["", {}], [/cr/i, /cr/i]], "n"=>[[{"$minElement"=>1}, {"$maxElement"=>1}]], "_id"=>[[{"$minElement"=>1}, {"$maxElement"=>1}]]}}], "oldPlan"=>{"cursor"=>"Btr
eeCursor st_1_n_1__id_1 multi", "indexBounds"=>{"st"=>[["", {}], [/cr/i, /cr/i]], "n"=>[[{"$minElement"=>1}, {"$maxElement"=>1}]], "_id"=>[[{"$minElement"=>1}, {"$maxElement
"=>1}]]}}, "server"=>"Arvinds-MacBook-Pro.local:27017"}
I suspect this is because of the only() modifier. Or is this a bug?
EDIT: I'm using Mongoid v3.1.4 and mongod v2.2
Here is the query that mongod is seeing from mongoid: Mon Jul 15 10:47:26 [conn14] runQuery called spl_development.merchants { $query: { st: { $regex: "cr", $options: "i" } }, $explain: true } Mon Jul 15 10:47:26 [conn14] query spl_development.merchants query: { $query: { st: { $regex: "cr", $options: "i" } }, $explain: true } ntoreturn:0 keyUpdates:0 locks(micros) r:212 nreturned:1 reslen:393 0ms
So the projection isn't being sent to the mongod layer and only just handles it in the application layer. Not ideal!