Reputation: 185
I have to search contents in all documents in particular collection of mongodb in .net mvc . I have tried with mongodb shell by creating index successfully like here .
db.collection_name.createIndex( { subject: "text" } )
db.collection_name.find( { $text: { $search: "search_word" } } )
It works fine . but when i put it in .net that gives me error . I googled it and got following solution for indexing .
collection.EnsureIndex(new IndexKeysBuilder().Ascending("subject"));
now how can i run this query db.collection_name.find( { $text: { $search: "coffee" } } )
.
I am trying in .net as following way .
collection.CreateIndex("subject":"text");
var query = collection.Find({ $text: { $search: "coffe" }});
but I am getting error on first line "represents text as series of unicode ....syntax error "
2nd line error "There is no argument given that corresponds to required formal parameters " And "unexpected character $ ".
any suggestion will be appreciated .
Upvotes: 16
Views: 16886
Reputation: 321
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();
Upvotes: 14
Reputation: 1
public List<T> FindSearch<T>(string collectionName, string searchWord) {
IMongoQuery query = Query.Text(searchWord);
List<T> find = getCollection<T>(collectionName).Find(query).ToList();
return find;
}
Upvotes: 0
Reputation: 9679
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; }
}
Upvotes: 17