Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Full text search in mongodb in .net

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 .

like image 462
naila naseem Avatar asked Dec 28 '16 06:12

naila naseem


1 Answers

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; } 
}
like image 189
Maksim Simkin Avatar answered Oct 07 '22 15:10

Maksim Simkin