mongodb/index.go

49 lines
942 B
Go
Raw Permalink Normal View History

2021-08-09 03:20:27 +00:00
package mongodb
import (
"context"
"fmt"
2024-07-09 10:06:15 +00:00
"go.mongodb.org/mongo-driver/bson"
2021-08-09 03:20:27 +00:00
"strings"
"time"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
// CreateIndex ...
func CreateIndex(colName string, ind mongo.IndexModel) {
// Get collection
col := db.Collection(colName)
if col == nil {
fmt.Printf("Collection %s not existed", colName)
return
}
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 {
2024-07-09 10:06:15 +00:00
var doc bson.D
2021-08-09 03:20:27 +00:00
for _, s := range key {
2024-07-09 10:06:15 +00:00
e := bson.E{
2021-08-09 03:20:27 +00:00
Key: s,
2024-07-09 10:06:15 +00:00
Value: 1,
2021-08-09 03:20:27 +00:00
}
if strings.HasPrefix(s, "-") {
2024-07-09 10:06:15 +00:00
e = bson.E{
2021-08-09 03:20:27 +00:00
Key: strings.Replace(s, "-", "", 1),
2024-07-09 10:06:15 +00:00
Value: -1,
2021-08-09 03:20:27 +00:00
}
}
doc = append(doc, e)
}
return mongo.IndexModel{Keys: doc}
2024-07-09 10:06:15 +00:00
}