-
慕雪6442864
我已经找到了解决方案: 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) }
-
人到中年有点甜
我编写了一个函数来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 -1mongodb 复合索引:AddIndex("mydb", "mycollection", bson.D{{"myFirstField", 1},{"mySecondField", -1}}) // to descending set it to -1mongodb 文本索引AddIndex("mydb", "mycollection", bson.D{{"myFirstTextField", "text"},{"mySecondTextField", "text"}})
-
Smart猫小萌
要使用官方 mongo go 驱动程序创建索引,您可以使用以下代码:// create IndexindexName, 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)您可以将其替换为您想要的索引配置。
-
慕虎7371278
您可以使用自定义选项和权重简单地创建文本索引,如下所示: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)
-
德玛西亚99
具有地理空间 (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)