5 回答

TA貢獻1812條經驗 獲得超5個贊
我已經找到了解決方案:
coll := db.Collection("test")
index := []mongo.IndexModel{
{
Keys: bsonx.Doc{{Key: "name", Value: bsonx.String("text")}},
},
{
Keys: bsonx.Doc{{Key: "createdAt", Value: bsonx.Int32(-1)}},
},
}
opts := options.CreateIndexes().SetMaxTime(10 * time.Second)
_, errIndex = coll.Indexes().CreateMany(context, index, opts)
if err != nil {
panic(errIndex)
}

TA貢獻1895條經驗 獲得超7個贊
我編寫了一個函數來MongoDB indexes documentation
為 MongoDB 支持的所有類型創建索引。
func AddIndex(dbName string, collection string, indexKeys interface{}) error {
? ? db := getNewDbClient() // get clients of mongodb connection
? ? serviceCollection := db.Database(dbName).Collection(collection)
? ? indexName, err := serviceCollection.Indexes().CreateOne(mtest.Background, mongo.IndexModel{
? ? ? ? Keys: indexKeys,
? ? })
? ? if err != nil {
? ? ? ? return err
? ? }
? ? fmt.Println(indexName)
? ? return nil
}
mongodb單字段索引:
AddIndex("mydb", "mycollection", bson.M{"myfieldname": 1}) // to descending set it to -1
mongodb 復合索引:
AddIndex("mydb", "mycollection", bson.D{{"myFirstField", 1},{"mySecondField", -1}}) // to descending set it to -1
mongodb 文本索引
AddIndex("mydb", "mycollection", bson.D{{"myFirstTextField", "text"},{"mySecondTextField", "text"}})

TA貢獻1911條經驗 獲得超7個贊
要使用官方 mongo go 驅動程序創建索引,您可以使用以下代碼:
// create Index
indexName, err := c.Indexes().CreateOne(
context.Background(),
mongo.IndexModel{
Keys: bson.M{
"time": 1,
},
Options: options.Index().SetUnique(true),
},
)
if err != nil {
log.Fatal(err)
}
fmt.Println(indexName)
您可以將其替換為您想要的索引配置。

TA貢獻1802條經驗 獲得超4個贊
您可以使用自定義選項和權重簡單地創建文本索引,如下所示:
mod := mongo.IndexModel{
Keys: bson.D{
{"title", "text"},
{"description", "text"},
},
// create UniqueIndex option
Options: options.Index().SetWeights(bson.D{
{"title", 9},
{"description", 3},
}),
}
collection.Indexes().CreateOne(context.Background(), mod)

TA貢獻1770條經驗 獲得超3個贊
具有地理空間 (2dsphere)、文本和單個字段。
models := []mongo.IndexModel{
{
Keys: bsonx.Doc{{Key: "username", Value: bsonx.String("text")}},
},
{
Keys: bsonx.Doc{{Key: "NearCoordinates", Value: bsonx.String("2dsphere")}},
},
{
Keys: bsonx.Doc{{Key: "password", Value: bsonx.Int32(1)}},
},
}
opts := options.CreateIndexes().SetMaxTime(20 * time.Second)
_, err := collectionName.Indexes().CreateMany(context.Background(), models, opts)
- 5 回答
- 0 關注
- 428 瀏覽
添加回答
舉報