Skip to content

Commit

Permalink
feat(iterator)
Browse files Browse the repository at this point in the history
  • Loading branch information
PxyUp committed Jul 17, 2019
1 parent 2609087 commit 25ebe5f
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 0 deletions.
1 change: 1 addition & 0 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ type MongoDbConnector interface {
GetAll(collectionName string, findPredicate bson.M, structToDeserialize interface{}) error
GetOneProject(collectionName string, findPredicate bson.M, projectFields bson.M, structToDeserialize interface{}) error
GetAllProject(collectionName string, findPredicate bson.M, projectFields bson.M, structToDeserialize interface{}) error
GetIterator(collectionName string, findPredicate bson.M, opts *mongo.MongoOptions) *mongo.MongoIterator
}

type CreateMongoConnector MongoDbConnector
Expand Down
30 changes: 30 additions & 0 deletions mongo/mongo.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,15 @@ type MongoConnector struct {
session *MgoSession
}

type MongoIterator struct {
*mgo.Iter
*mgo.Session
}

type MongoOptions struct {
Projection *bson.M
}

type MgoSession struct {
session *mgo.Session
isConnected bool
Expand Down Expand Up @@ -130,3 +139,24 @@ func (c *MongoConnector) Disconnect() {
c.session.session.Close()
c.session.isConnected = false
}

func (c *MongoConnector) GetIterator(collectionName string, findPredicate bson.M, opts *MongoOptions) *MongoIterator {
sessionCopy := c.session.session.Copy()
collection := sessionCopy.DB(c.session.dataBaseName).C(collectionName)
query := collection.Find(findPredicate)
if opts != nil {
if opts.Projection != nil {
query = query.Select(*opts.Projection)
}
}
return &MongoIterator{query.Iter(), sessionCopy}
}

func (iter *MongoIterator) Close() error {
err := iter.Iter.Close()
if err != nil {
return err
}
iter.Session.Close()
return nil
}

0 comments on commit 25ebe5f

Please sign in to comment.