mongodb/index.go

51 lines
1.0 KiB
Go
Raw Normal View History

2021-08-09 03:20:27 +00:00
package mongodb
import (
"context"
"fmt"
"strings"
"time"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"go.mongodb.org/mongo-driver/x/bsonx"
)
// CreateIndex ...
func CreateIndex(colName string, ind mongo.IndexModel) {
2021-10-07 16:37:41 +00:00
fmt.Println("db name:", db.Name())
2021-08-09 03:20:27 +00:00
// Get collection
col := db.Collection(colName)
if col == nil {
fmt.Printf("Collection %s not existed", colName)
return
}
2021-10-07 16:34:42 +00:00
fmt.Println("ind", ind)
2021-08-09 03:20:27 +00:00
opts := options.CreateIndexes().SetMaxTime(time.Minute * 10)
_, err := col.Indexes().CreateOne(context.Background(), ind, opts)
if err != nil {
fmt.Printf("Index collection %s err: %v", col.Name(), err)
}
}
// NewIndexKey ...
func NewIndexKey(key ...string) mongo.IndexModel {
var doc bsonx.Doc
for _, s := range key {
e := bsonx.Elem{
Key: s,
Value: bsonx.Int32(1),
}
if strings.HasPrefix(s, "-") {
e = bsonx.Elem{
Key: strings.Replace(s, "-", "", 1),
Value: bsonx.Int32(-1),
}
}
doc = append(doc, e)
}
return mongo.IndexModel{Keys: doc}
}