How to Implement MongoDB TextSearch with C#

2015/01/312 min read
bookmark this

Table of Contents

  1. Introduction
  2. Add Text Index to the Collection
  3. Call Text Search Functions
  4. MongoDB Version Requirements
  5. Conclusion

Introduction

This post provides a simple code snippet to implement MongoDB text search using C#. MongoDB needs to be version 2.6 or higher for text search to work properly.

Add Text Index to the Collection

First, add a 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));

Call Text Search Functions

Now, call the 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 Version Requirements

MongoDB needs to be version 2.6 or higher for text search functionality to work correctly.

Conclusion

That's it — now you can enjoy text search in MongoDB with C#. By creating a text index on the desired fields and using CommandDocument to run the text search, you can easily implement full-text search in your C# application.