I'm trying to do a full text search on a collection, but in order to do that I need to create a text index. How can I create a text index on two fields?
I know that I must use a thing as this:
opts := options.CreateIndexes().SetMaxTime(10 * time.Second)
idxFiles := []mongo.IndexModel{
{
Keys: bsonx.Doc{{"name": "text"}},
},
}
db.Collection("mycollection").Indexes().CreateMany(context, idx, opts)
To create indexes using the official mongo go driver you can use the following code:
// 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)
You can replace it with your desired index configuration.
I have founded the solution:
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)
}