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)
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)
}
From MongoDB indexes documentation
I wrote a function to create an index for all types MongoDB supported.
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 single field index:
AddIndex("mydb", "mycollection", bson.M{"myfieldname": 1}) // to descending set it to -1
mongodb Compound index:
AddIndex("mydb", "mycollection", bson.D{{"myFirstField", 1},{"mySecondField", -1}}) // to descending set it to -1
mongodb Text index
AddIndex("mydb", "mycollection", bson.D{{"myFirstTextField", "text"},{"mySecondTextField", "text"}})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With