使用Golang对MongoDB创建索引



  • 使用Golang对MongoDB创建索引


    1、下载MongoDB驱动

    go get github.com/mongodb/mongo-go-driver 
    

    2、连接MongoDB

    import (
    	"context"
    	"log"
    
    	"go.mongodb.org/mongo-driver/mongo"
    	"go.mongodb.org/mongo-driver/mongo/options"
    	"go.mongodb.org/mongo-driver/mongo/readpref"
    )
    
    client, err := mongo.NewClient(options.Client().ApplyURI("mongodb://127.0.0.1:27017"))
    if err != nil {
        log.Fatal(err)
    }
    err = client.Connect(context.TODO())
    if err != nil {
        log.Fatal(err)
    }
    

    3、测试连接是否成功

    if err := client.Ping(context.TODO(), readpref.Primary()); err != nil {
        log.Fatal(err)
    }
    

    4、创建唯一索引

    // Email可能为空(注册时被必填项),为了防止
    // 空值的唯一冲突,所以设置成稀疏索引
    opEmail := options.Index()
    opEmail.SetName("email_index")
    opEmail.SetUnique(true)
    opEmail.SetSparse(true)
    
    // 默认唯一索引配置
    opDef := options.Index()
    opDef.SetName("def_index")
    opDef.SetUnique(true)
    
    // 使用配置生成索引对象
    modDef := mongo.IndexModel{
    	Keys: bson.M{
    		"nickname": 1,
    		"phone":    1,
    	}, Options: opDef,
    }
    modEmail := mongo.IndexModel{
    	Keys: bson.M{
    		"email": 1,
    	}, Options: opEmail,
    }
    
    // 为Collection配置索引,Indexes().CreateMany()可以一次
    // 指定多个索引对象
    col := client.Database("db_name").Collection("User")
    col.Indexes().CreateMany(context.TODO(), []mongo.IndexModel{modDef, modEmail})
    

    5、测试

    type RecUserI struct {
    	Nickname string             `bson:"nickname"`
    	Phone    string             `bson:"phone"`
    	Email    string             `bson:"email"`
    }
    // 邮箱为空值,并且使电话冲突
    result, err := col.InsertOne(context.TODO(), RecUserINickname: "guaik0", Phone: "18888888888"})
    if err != nil {
    	log.Fatal(err)
    	return
    }
    result, err = col.InsertOne(context.TODO(), RecUserINickname: "guaik1", Phone: "18888888888"})
    if err != nil {
    	log.Fatal(err)
    	return
    }
    

Log in to reply