Eng Sabreen Saber Eng Sabreen Saber - 25 days ago 6
C# Question

how to search on mongodb by using runcommand

This is my code... but runcommand doesn't get any results

Notice : "title" is an indexed field

var mongoClient = new MongoClient(ConfigurationManager.AppSettings["connectionString"]);

var server = mongoClient.GetServer();
mongodatabase = server.GetDatabase("Htmlattachment2");
MongoCollection<Department> attachments = mongodatabase.GetCollection<Department>("attachment2");

attachments.EnsureIndex(new IndexKeysBuilder().Ascending("title"));
attachments.Insert(new BsonDocument("title", "The quick brown fox"));

var t = attachments.GetIndexes().ToList();
//foreach (Attachements emp in attachments.FindAll())
//{ }

var textSearchCommand = new CommandDocument
{ "text","title" },
{ "search", textBox1.Text }

var commandResult = mongodatabase.RunCommand(textSearchCommand);

var response = commandResult.Response["results"].AsBsonArray;
foreach (BsonDocument result in response)
// process result

Answer Source

It might be easier if you just used LINQ to perform queries. There is a tutorial on how use LINQ with MongoDB here. Note that the MongoDB C# driver translates the LINQ queries to run on the database as native Mongo queries.