Uploaded image for project: 'Documentation'
  1. Documentation
  2. DOCS-3226

Mention how sparse indexing works with compound and geospatial indexes

    • Type: Icon: Task Task
    • Resolution: Done
    • Priority: Icon: Minor - P4 Minor - P4
    • v1.3.6
    • Affects Version/s: None
    • Component/s: manual
    • Labels:
      None

      The following pages refer to sparse indexes:

      I came across old documentation in the PHP driver stating that sparse indexes only worked with single-field indexes. Thinking that was incorrect, I decided to try them with compound indexes and found that they will index any documents with at least one of the included fields:

      > db.foo.drop()
      true
      > db.foo.ensureIndex({x:1,y:1},{sparse:true})
      {
      	"createdCollectionAutomatically" : true,
      	"numIndexesBefore" : 1,
      	"numIndexesAfter" : 2,
      	"ok" : 1
      }
      > db.foo.insert({x:1})
      WriteResult({ "nInserted" : 1 })
      > db.foo.insert({y:1})
      WriteResult({ "nInserted" : 1 })
      > db.foo.insert({x:2,y:2})
      WriteResult({ "nInserted" : 1 })
      > db.foo.insert({z:1})
      WriteResult({ "nInserted" : 1 })
      > db.foo.find().hint("x_1_y_1")
      { "_id" : ObjectId("535532a190f51aaf07927fbb"), "y" : 1 }
      { "_id" : ObjectId("5355329f90f51aaf07927fba"), "x" : 1 }
      { "_id" : ObjectId("535532a590f51aaf07927fbc"), "x" : 2, "y" : 2 }
      

      Also, our current documentation says that sparse only works with asc/desc indexes. It appears to work with geospatial indexes as well.

      > db.foo.drop()
      true
      > db.foo.ensureIndex({loc:"2d"},{sparse:true})
      {
      	"createdCollectionAutomatically" : true,
      	"numIndexesBefore" : 1,
      	"numIndexesAfter" : 2,
      	"ok" : 1
      }
      > db.foo.insert({x:1})
      WriteResult({ "nInserted" : 1 })
      > db.foo.insert({loc:[0,0]})
      WriteResult({ "nInserted" : 1 })
      > db.foo.find({loc:{$near:[0,0]}})
      { "_id" : ObjectId("5355322e90f51aaf07927fb9"), "loc" : [ 0, 0 ] }
      

      I didn't test text indexes, but that would be another thing to confirm.

            Assignee:
            kay.kim@mongodb.com Kay Kim (Inactive)
            Reporter:
            jmikola@mongodb.com Jeremy Mikola
            Votes:
            0 Vote for this issue
            Watchers:
            2 Start watching this issue

              Created:
              Updated:
              Resolved:
              9 years, 49 weeks, 5 days ago