From 5c7df883df762851cc5dec8af9b9a0a87060576b Mon Sep 17 00:00:00 2001 From: adrienpetel Date: Fri, 25 Aug 2017 15:47:03 +0400 Subject: [PATCH] add DropAllIndexes() method Create a new method to drop all the indexes of a collection in a single call --- session.go | 36 +++++++++++++++++++++++------------- session_test.go | 25 +++++++++++++++++++++++++ 2 files changed, 48 insertions(+), 13 deletions(-) diff --git a/session.go b/session.go index 6827dffe5..d18277be4 100644 --- a/session.go +++ b/session.go @@ -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. @@ -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() diff --git a/session_test.go b/session_test.go index 912f1c92a..e29221cb4 100644 --- a/session_test.go +++ b/session_test.go @@ -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)