Full text search in mongodb in .net

℡╲_俬逩灬. 提交于 2020-01-02 03:15:09

问题


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 .


回答1:


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; } 
}



回答2:


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;
}


来源:https://stackoverflow.com/questions/41356544/full-text-search-in-mongodb-in-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!