1. 登录mongo,创建数据库
mongosh -u $username -p $password
use test
2. 查看集合索引
db.$collection_name.getIndexes()
为不存在的集合创建字段唯一索引
package main
import (
"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 MongoDB
err = 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 main
import (
"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 MongoDB
err = 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)会报创建索引错误,说明针对存在重复值的字段,无法创建唯一索引