How To Implement Mongodb TextSearch with C#

2015/01/311 min read
bookmark this
Responsive image

Table of Contents

  1. First add text index to the collection.
  2. Now, call text search functions
  3. Mongodb need to be 2.6 or higher

First add text index to the collection.

// add text index to the item
 string[] textIndex = new string[] { "Name", "ListItem.Name", "ListItem.Name2", "AnotherListItem.Name"};
            string indexName = string.Join("_text_", textIndex) + "_text";
            if (collection.IndexExistsByName(indexName))
            {
                collection.DropIndexByName(indexName);
            }
            collection.EnsureIndex(new IndexKeysBuilder().Text(textIndex));

Now, call text search functions

var textSearchCommand = new CommandDocument
            {
              { "text", "CollectionName" },
              { "search", yourSearchTargetText}
            };

            var commandResult = Mongo.Database.RunCommand(textSearchCommand);
            var yourCollectionItems = commandResult.Response["results"].AsBsonArray.Select(o =>
            {
                return BsonSerializer.Deserialize(o["obj"].AsBsonDocument);
            });

Mongodb need to be 2.6 or higher

That's it, now you can enjoy text search in MongoDB.