Reputation: 1012
I am using MongoDB in c#. To search a 'question' in the 'knowledge' collection, this is my code.
var collection = _database.GetCollection<BsonDocument>("knowledge");
var filter = Builders<BsonDocument>.Filter.Eq("question", question);
var results = await collection.Find(filter).ToListAsync();
Instead of this I want to search a 'question' that contains the given words. I want to search a pattern simply like following in MongoDB.
db.stores.find( { $text: { $search: "java \"coffee shop\"" } } )
I found this in the Stack.
collection.Indexes.CreateOne(Builders<searchFileByAuthor>.IndexKeys.Text(x=>x.subject));
collection.Find(Builders<searchFileByAuthor>.Filter.Text("coffe")).ToList();
Full text search in mongodb in .net
I am not familiar with using MongoDB in c# though. How should I modify my code to create a text index and search a pattern? How to do this in MongoDB .NET Driver version 2.4.4?
Upvotes: 2
Views: 2766
Reputation: 41
you can using full-text search
Collection.Indexes.CreateOne(new CreateIndexModel<T>(Builders<T>.IndexKeys.Text("$**")));
//build filter and query
var key = txtSearchKey.Text.ToLower().Trim();
var filter = Builders<EntityObject>.Filter.Text(key);
Upvotes: 2
Reputation: 5603
To create search patterns you can use the Regex builder. Example to match either "java" or "coffee shop" in the description field:
var collection = _database.GetCollection<BsonDocument>("knowledge");
var builder = Builders<BsonDocument>.Filter;
var filter = builder.Regex("description", "(java)") | builder.Regex("description", "(coffee shop)");
var result = collection.Find(filter).ToList();
Upvotes: 4