Full text search in mongodb in .net
I could create text indexes with this command:
collection.Indexes.CreateOne(Builders<searchFileByAuthor>.IndexKeys.Text(x=>x.subject));
And than i could query index this way:
collection.Find(Builders<searchFileByAuthor>.Filter.Text("coffe")).ToList();
searchFileByAuthor
is just my fake class with subject field:
public class searchFileByAuthor
{
public int Id { get; set; }
public string subject { get; set; }
}
Maksim Simkin answer is correct, althought it is obsolete. The updated version would be:
collection.Indexes.CreateOne(new CreateIndexModel<YourClass>(Builders<YourClass>.IndexKeys.Text(x => x.something)));
or, if you would like to use the Wildcard Indexing (to index the entire document), you could do like this:
collection.Indexes.CreateOne(new CreateIndexModel<YourClass>(Builders<YourClass>.IndexKeys.Text("$**")));
or maybe you want/have more indexes for some reason, than do this:
var indexWildcardTextSearch = new CreateIndexModel<YourClass>(Builders<YourClass>.IndexKeys.Text("$**"));
List<CreateIndexModel<YourClass>> indexes = new List<CreateIndexModel<YourClass>>();
indexes.Add(indexWildcardTextSearch);
collection.Indexes.CreateMany(indexes);
And to query, it remains the same:
collection.Find(Builders<YourClass>.Filter.Text("something")).ToList();