0

I am using the new 2.0 C# Driver for MongoDB. I am trying to create an autocomplete search box on my website.

I have a simple collection that has ID, Symbol, and Name:

/* 0 */ { "_id" : ObjectId("55743a1dbc8d1c60942ac524"), "Symbol" : "A", "Name" : "Agilent Technologies, Inc. Comm" }

/* 1 */ { "_id" : ObjectId("55743a2dbc8d1c60942ac525"), "Symbol" : "AA", "Name" : "Alcoa Inc. Common Stock" }

/* 2 */ { "_id" : ObjectId("55743a2dbc8d1c60942ac526"), "Symbol" : "AAC", "Name" : "AAC Holdings, Inc. Common Stock" }

/* 3 */ { "_id" : ObjectId("55743a2dbc8d1c60942ac527"), "Symbol" : "AAL", "Name" : "American Airlines Group, Inc." }

I created a text index using this command:

db.StockLookups.createIndex({Symbol: "text", Name: "text"})

I have the following method in my code:

public async Task<List<StockLookup>> SearchAsync(string searchString)
{
    var filter = Builders<StockLookup>.Filter.Text(searchString);

    return await _collection.Find(filter)
        .ToListAsync();
}

However, it is not returning the desired results. If I type in "AAL" I get back American Airlines which is what I want.

However, if I type in "AA" I only get back Alcoa. In this case I would want it to return Alcoa, AAC Holdings, and American Airlines.

What am I doing wrong and how can I correct the problem?

cramopy
  • 3,459
  • 6
  • 28
  • 42
jkruer01
  • 2,175
  • 4
  • 32
  • 57
  • 3
    From the mongodb documentation: "The $text operator matches on the complete stemmed word. So if a document field contains the word blueberry, a search on the term blue will not match. However, blueberry or blueberries will match." – Brian Shamblen Jun 07 '15 at 15:10
  • Yeah, I saw that after posting this question. So what kind of query do I need to be able to get the results that I am looking for? I want a case insensitive search where either the Name or the Symbol field contains the text that is entered. – jkruer01 Jun 07 '15 at 17:24
  • 1
    You'll need to perform a Regex search. http://stackoverflow.com/questions/8382307/mongodb-c-sharp-query-for-like-on-string – Brian Shamblen Jun 07 '15 at 17:55
  • Thanks! That worked. If you post an answer with that response, I will accept it as the answer. – jkruer01 Jun 08 '15 at 11:27

0 Answers0