Skip to content

Instantly share code, notes, and snippets.

@rhcarvalho
Created August 2, 2012 13:06
Show Gist options
  • Save rhcarvalho/3236931 to your computer and use it in GitHub Desktop.
Save rhcarvalho/3236931 to your computer and use it in GitHub Desktop.
MongoDB convering indexes
$ mongo
MongoDB shell version: 2.0.4
connecting to: test
> doc = {_id: 42, name: "propedeutica", power: 0.92}
{ "_id" : 42, "name" : "propedeutica", "power" : 0.92 }
> db.foobar.insert(doc)
> db.foobar.ensureIndex({name: 1})
> db.foobar.find({name: "propedeutica"}).explain()
{
"cursor" : "BtreeCursor name_1",
"nscanned" : 1,
"nscannedObjects" : 1,
"n" : 1,
"millis" : 0,
"nYields" : 0,
"nChunkSkips" : 0,
"isMultiKey" : false,
"indexOnly" : false,
"indexBounds" : {
"name" : [
[
"propedeutica",
"propedeutica"
]
]
}
}
> db.foobar.find({name: "propedeutica"}, {_id: 0}).explain()
{
"cursor" : "BtreeCursor name_1",
"nscanned" : 1,
"nscannedObjects" : 1,
"n" : 1,
"millis" : 0,
"nYields" : 0,
"nChunkSkips" : 0,
"isMultiKey" : false,
"indexOnly" : false,
"indexBounds" : {
"name" : [
[
"propedeutica",
"propedeutica"
]
]
}
}
> db.foobar.find({name: "propedeutica"}, {_id: 0})
{ "name" : "propedeutica", "power" : 0.92 }
> db.foobar.find({name: "propedeutica"}, {_id: 0, power: 0})
{ "name" : "propedeutica" }
// This is not indexOnly because MongoDB cannot determine that 'name' is the only field in the results
> db.foobar.find({name: "propedeutica"}, {_id: 0, power: 0}).explain()
{
"cursor" : "BtreeCursor name_1",
"nscanned" : 1,
"nscannedObjects" : 1,
"n" : 1,
"millis" : 0,
"nYields" : 0,
"nChunkSkips" : 0,
"isMultiKey" : false,
"indexOnly" : false,
"indexBounds" : {
"name" : [
[
"propedeutica",
"propedeutica"
]
]
}
}
// Now note that this query is *indexOnly*, since you only ask for the 'name' field
> db.foobar.find({name: "propedeutica"}, {_id: 0, name: 1}).explain()
{
"cursor" : "BtreeCursor name_1",
"nscanned" : 1,
"nscannedObjects" : 1,
"n" : 1,
"millis" : 0,
"nYields" : 0,
"nChunkSkips" : 0,
"isMultiKey" : false,
"indexOnly" : true,
"indexBounds" : {
"name" : [
[
"propedeutica",
"propedeutica"
]
]
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment