Search code examples
mongodbgoindexingtext-search

mongo-go-driver (IndexNotFound) text index required for $text query


I'm using mongo-go-driver and trying to use text search

I'm creating index like this

    opts := options.CreateIndexes().SetMaxTime(10 * time.Second)
    db.Collection("my_collection").Indexes().CreateMany(
        context.Background(),
        []mongo.IndexModel{
            {
                Keys: bsonx.Doc{{"title", bsonx.Int32(-1)}},
            },
            {
                Keys: bsonx.Doc{{"info.tags", bsonx.Int32(-1)}},
            },
        },
        opts,
    )

...and while querying I'm doing this

    collection := db.Collection("my_collection")

    cur, err := collection.Find(context.Background(), bson.M{ "$text": bson.M{ "$search": query }})

I get this when I call the query

 (IndexNotFound) text index required for $text query
  exit status 1

Solution

  • You need to have a text index on atleast 1 field for the query to work. Try creating a text index on any field and try again