Full Text Search in MongoDB in .Net or C#

3,641 views
Skip to first unread message

nailan...@gmail.com

unread,
Dec 28, 2016, 12:44:07 PM12/28/16
to mongodb-user

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 $ ".


please explain how can i full text search with mongodb in .net mvc easily .

Wan Bachtiar

unread,
Jan 5, 2017, 2:00:03 AM1/5/17
to mongodb-user

please explain how can i full text search with mongodb in .net mvc easily .

Hi,

First, you need to create the text index by using:

var keys = Builders<BsonDocument>.IndexKeys.Text("subject");
collection.Indexes.CreateOne(keys);

Note that it’s using Text() instead of Ascending().

To perform the text search you can do as below example:

var filter = Builders<BsonDocument>.Filter.Text("coffe");
var result = collection.Find(filter).ToList();

I would recommend to review MongoDB Driver Admin QuickTour for more examples. You may also find useful the free online course on MongoDB University on MongoDB .Net/C# M101N: MongoDB for .NET Developers. The next session starts on 10th January, there’s plenty of time to register.

Regards,

Wan.

Reply all
Reply to author
Forward
0 new messages