1 Star 0 Fork 0

carlmax_my/console-core-go

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
mongo_indexes.go 1.17 KB
一键复制 编辑 原始数据 按行查看 历史
carlmax_my 提交于 2024-12-02 21:32 . init project
package mongo
import (
"context"
"log"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
type indexInfo struct {
Key map[string]any `bson:"key"`
Name string `bson:"name"`
Unique bool `bson:"unique"`
}
func (c *Collection[T]) GetIndexes() (indexes map[string]any) {
indexes = make(map[string]any)
cursor, err := c.Indexes().List(context.TODO())
if err != nil {
log.Println("GetIndexes.err: " + err.Error())
return
}
ret := make([]indexInfo, 0)
if err = cursor.All(context.TODO(), &ret); err != nil {
log.Println("cursor.All.err: " + err.Error())
}
for _, i := range ret {
if len(i.Key) == 1 {
for key := range i.Key {
indexes[key] = i.Key[key]
}
} else {
// not supported yet: compound indexes
log.Printf("not supported yet: compound indexes\n")
}
}
return
}
func (c *Collection[T]) SetIndexes(key string, unique bool) error {
indexModel := mongo.IndexModel{
Keys: bson.D{{Key: key, Value: 1}},
Options: options.Index().SetUnique(unique),
}
if _, err := c.Indexes().CreateOne(context.TODO(), indexModel); err != nil {
return err
}
return nil
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/carlmax_my/console-core-go.git
git@gitee.com:carlmax_my/console-core-go.git
carlmax_my
console-core-go
console-core-go
v0.0.5

搜索帮助

0d507c66 1850385 C8b1a773 1850385