go mongo 唯一索引创建

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)会报创建索引错误,说明针对存在重复值的字段,无法创建唯一索引
  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

赴前尘

喜欢我的文章?请我喝杯咖啡吧!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值