Skip to content

Commit

Permalink
add DropAllIndexes() method (#25)
Browse files Browse the repository at this point in the history
Create a new method to drop all the indexes of a collection
in a single call
  • Loading branch information
feliixx authored and domodwyer committed Aug 30, 2017
1 parent 1519fd3 commit 454da02
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 13 deletions.
36 changes: 23 additions & 13 deletions session.go
Original file line number Diff line number Diff line change
Expand Up @@ -1499,6 +1499,29 @@ func (c *Collection) DropIndexName(name string) error {
return nil
}

// DropAllIndexes drops all the indexes from the c collection
func (c *Collection) DropAllIndexes() error {
session := c.Database.Session
session.ResetIndexCache()

session = session.Clone()
defer session.Close()

db := c.Database.With(session)
result := struct {
ErrMsg string
Ok bool
}{}
err := db.Run(bson.D{{"dropIndexes", c.Name}, {"index", "*"}}, &result)
if err != nil {
return err
}
if !result.Ok {
return errors.New(result.ErrMsg)
}
return nil
}

// nonEventual returns a clone of session and ensures it is not Eventual.
// This guarantees that the server that is used for queries may be reused
// afterwards when a cursor is received.
Expand All @@ -1512,19 +1535,6 @@ func (session *Session) nonEventual() *Session {

// Indexes returns a list of all indexes for the collection.
//
// For example, this snippet would drop all available indexes:
//
// indexes, err := collection.Indexes()
// if err != nil {
// return err
// }
// for _, index := range indexes {
// err = collection.DropIndex(index.Key...)
// if err != nil {
// return err
// }
// }
//
// See the EnsureIndex method for more details on indexes.
func (c *Collection) Indexes() (indexes []Index, err error) {
cloned := c.Database.Session.nonEventual()
Expand Down
25 changes: 25 additions & 0 deletions session_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3478,6 +3478,31 @@ func (s *S) TestEnsureIndexDropIndexName(c *C) {
c.Assert(err, ErrorMatches, "index not found.*")
}

func (s *S) TestEnsureIndexDropAllIndexes(c *C) {
session, err := mgo.Dial("localhost:40001")
c.Assert(err, IsNil)
defer session.Close()

coll := session.DB("mydb").C("mycoll")

err = coll.EnsureIndexKey("a")
c.Assert(err, IsNil)

err = coll.EnsureIndexKey("b")
c.Assert(err, IsNil)

err = coll.DropAllIndexes()
c.Assert(err, IsNil)

sysidx := session.DB("mydb").C("system.indexes")

err = sysidx.Find(M{"name": "a_1"}).One(nil)
c.Assert(err, Equals, mgo.ErrNotFound)

err = sysidx.Find(M{"name": "b_1"}).One(nil)
c.Assert(err, Equals, mgo.ErrNotFound)
}

func (s *S) TestEnsureIndexCaching(c *C) {
session, err := mgo.Dial("localhost:40001")
c.Assert(err, IsNil)
Expand Down

0 comments on commit 454da02

Please sign in to comment.