您的位置:首页 > 游戏 > 游戏 > go mongo 唯一索引创建

go mongo 唯一索引创建

2024/10/6 16:31:17 来源:https://blog.csdn.net/qq_36940806/article/details/139314322  浏览:    关键词:go mongo 唯一索引创建

1. 登录mongo,创建数据库

mongosh -u $username -p $password
use test

2. 查看集合索引

db.$collection_name.getIndexes()

为不存在的集合创建字段唯一索引

package mainimport ("context""fmt""log""time""go.mongodb.org/mongo-driver/bson""go.mongodb.org/mongo-driver/mongo""go.mongodb.org/mongo-driver/mongo/options""go.mongodb.org/mongo-driver/mongo/readpref"
)func main() {ctx := context.Background()addr := "127.0.0.1:27027"database := "test"userName := "test"password := "123456"var maxPoolSize uint64 = 100// Setup MongoDB client// 建立连接client, err := mongo.Connect(ctx,options.Client().// 连接地址ApplyURI(fmt.Sprintf("mongodb://%s/%s", addr, database)).SetAuth( // 设置验证参数options.Credential{Username:   userName, // 用户名Password:   password, // 密码AuthSource: database,}).// 设置连接数SetMaxPoolSize(maxPoolSize))if err != nil {log.Fatal(err)}ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)defer cancel()// Ping MongoDBerr = client.Ping(ctx, readpref.Primary())if err != nil {log.Fatalf("Failed to ping mongo: %v", err)}db := client.Database("sec_ped")collection := db.Collection("nonexistent_collection")// 定义索引模型indexModel := mongo.IndexModel{Keys:    bson.D{{Key: "fieldname", Value: 1}}, // 索引键Options: options.Index().SetName("index_on_fieldname").SetUnique(true),}// 创建索引indexName, err := collection.Indexes().CreateOne(ctx, indexModel)if err != nil {log.Fatal(err)}fmt.Printf("Created index %s\n", indexName)// 关闭客户端连接if err := client.Disconnect(context.TODO()); err != nil {log.Fatal(err)}fmt.Println("Connection to MongoDB closed.")
}
  • 结论
    (1)多次运行不会报错,说明可以重复创建索引
    (2)可以为不存在的集合创建索引

为存在重复字段的集合创建唯一索引

package mainimport ("context""fmt""log""time""go.mongodb.org/mongo-driver/bson""go.mongodb.org/mongo-driver/mongo""go.mongodb.org/mongo-driver/mongo/options""go.mongodb.org/mongo-driver/mongo/readpref"
)func main() {ctx := context.Background()addr := "127.0.0.1:27027"database := "test"userName := "test"password := "123456"var maxPoolSize uint64 = 100// Setup MongoDB client// 建立连接client, err := mongo.Connect(ctx,options.Client().// 连接地址ApplyURI(fmt.Sprintf("mongodb://%s/%s", addr, database)).SetAuth( // 设置验证参数options.Credential{Username:   userName, // 用户名Password:   password, // 密码AuthSource: database,}).// 设置连接数SetMaxPoolSize(maxPoolSize))if err != nil {log.Fatal(err)}ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)defer cancel()// Ping MongoDBerr = client.Ping(ctx, readpref.Primary())if err != nil {log.Fatalf("Failed to ping mongo: %v", err)}db := client.Database("sec_ped")collection := db.Collection("nonexistent_collection")// 插入两条重复的数据docs := []interface{}{bson.D{{Key: "fieldname", Value: "value1"}, {Key: "otherfield", Value: "data1"}},bson.D{{Key: "fieldname", Value: "value1"}, {Key: "otherfield", Value: "data2"}},}insertManyResult, err := collection.InsertMany(ctx, docs)if err != nil {log.Fatal(err)}fmt.Printf("Inserted documents: %v\n", insertManyResult.InsertedIDs)// 定义索引模型indexModel := mongo.IndexModel{Keys: bson.D{{Key: "fieldname", Value: 1}}, // 索引键Options: options.Index().SetName("index_on_fieldname").SetUnique(true),}// 创建索引indexName, err := collection.Indexes().CreateOne(ctx, indexModel)if err != nil {log.Fatal(err)}fmt.Printf("Created index %s\n", indexName)// 关闭客户端连接if err := client.Disconnect(context.TODO()); err != nil {log.Fatal(err)}fmt.Println("Connection to MongoDB closed.")
}
  • 结论
    (1)会报创建索引错误,说明针对存在重复值的字段,无法创建唯一索引

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com