github.com/seeker-insurance/kit@v0.0.13/db/mongo/mongo.go (about)

     1  package mongo
     2  
     3  import (
     4  	"errors"
     5  
     6  	"github.com/globalsign/mgo"
     7  	"github.com/spf13/viper"
     8  	"github.com/spf13/cobra"
     9  )
    10  
    11  var (
    12  	MDb      *mgo.Database
    13  	Error    error
    14  	MongoUrl string
    15  	Msession *mgo.Session
    16  )
    17  
    18  func init() {
    19  	cobra.OnInitialize(connectG)
    20  }
    21  
    22  func connectG() {
    23  	MongoUrl = viper.GetString("mongo_url")
    24  	if len(MongoUrl) == 0 {
    25  		Error = errors.New("Missing mongo_url")
    26  	} else {
    27  		if Msession, Error = mgo.Dial(MongoUrl); Error == nil {
    28  			info, _ := mgo.ParseURL(MongoUrl)
    29  			Msession.SetMode(mgo.Monotonic, true)
    30  			MDb = Msession.DB(info.Database)
    31  		}
    32  	}
    33  }
    34  
    35  func Connect() (*mgo.Database, error){
    36  	url := viper.GetString("mongo_url")
    37  	if len(url) == 0 {
    38  		return nil, errors.New("Missing mongo_url")
    39  	}
    40  
    41  	mSession, err := mgo.Dial(MongoUrl)
    42  	if err != nil {
    43  		return nil, err
    44  	}
    45  
    46  	info, _ := mgo.ParseURL(url)
    47  	mSession.SetMode(mgo.Monotonic, true)
    48  
    49  	return mSession.DB(info.Database), nil
    50  }
    51  
    52  //InCollection returns whether document(s) matching the query the specified collection exist
    53  func InCollection(collection *mgo.Collection, selector interface{}) bool {
    54  	n, _ := collection.Find(selector).Count()
    55  	return n > 0
    56  }
    57  
    58  //UniqueInCollection returns whether one and only one document matching the query in the specified collection exists.
    59  func UniqueInCollection(collection *mgo.Collection, selector interface{}) bool {
    60  	n, _ := collection.Find(selector).Count()
    61  	return n == 1
    62  }
    63  
    64  func EnsureLocationIndex(collection *mgo.Collection) error {
    65  	index := mgo.Index{
    66  		Key: []string{"$2dsphere:location"},
    67  	}
    68  	return collection.EnsureIndex(index)
    69  }