Indexing and Query Optimizer - Kevin Hanson, 10gen
MongoDB LA 2012
MongoDB supports a wide range of indexing options to enable fast querying of your data. In this talk we’ll cover how indexing works, the various indexing options, and cover use cases where each might be useful
Indexes Will Slow Writes • Indexes Take Up Space • Index Maintenance Will Cause Writes • “unique” Parameter Forces Uniqueness db.blogs.save({ ... title: "My first blog" }); db.blogs.ensureIndex({title: 1}, {unique: true}) Monday, January 23, 12
is present • Reduces size of index • Limited to a single field db.blogs.ensureIndex({loc: 1}, {sparse: true}) // loc key stored for Blayze & Cody only db.blogs.save({author: "Kevin"}) db.blogs.save({author: "Blayze", loc: null}) db.blogs.save({author: "Cody", loc: "AZ"}) Sparse Indexes Monday, January 23, 12
{sparse:true,unique:true}); db.blogs.save({url:"www.10gen.com"}) // Can only have a single null value db.blogs.save({url:null}) db.blogs.save({url:null}) E11000 duplicate key error index: test.blogs.$url_1 dup key: { : null } // Can have multiple missing values db.blogs.save({author:"Sally"}) db.blogs.save({author:"Rick"}) Unique Sparse Indexes Monday, January 23, 12
So use them! • Indexes Take Up Space and Slow Writes • So only use them when you need them! • Not Sure? • Use Query Profiling and Explain Monday, January 23, 12