Turtle Turtle - 1 month ago 23
C# Question

Filter MongoDB database and pull document into DataGridView with c#

I'm trying to filter a MongoDB database with the text stored inside a textbox. For example I would put "turtle" and all the entries that have the "Name" "turtle" will appear inside a datagridview.

Here is the code for the button which connects to the MongoDB database, gets the database name and the "users" collection and applies the filter of whatever is inside the textbox txtName.

private void btnSearch_Click(object sender, EventArgs e)
{
var client = new MongoClient("mongodb://localhost");

var database = client.GetDatabase("test");

var collection = database.GetCollection<BsonDocument>("users");

var filter = Builders<BsonDocument>.Filter.Eq("Name", txtName.Text);
}


I'm not sure where to go next. I need to then bind all data into the datagridviews datasource to match the records that have the name turtle.

dgvAll.DataSource = somevariable;


Thanks

Answer

To get your data out of the database

var results = collection.Find(filter).ToList();

This will give you a list of objects that you an bind the same as you would another other collection.

You may want to look into strongly typing your models instead of using text queries. For example

public class MyModel
{
    public string SomeProperty { get; set; }

    public string SomeOtherProperty { get; set; }
}

And when you query

private void btnSearch_Click(object sender, EventArgs e)
{
    var client = new MongoClient("mongodb://localhost");

    var database = client.GetDatabase("test");

    var collection = database.GetCollection<MyModel>("users");

    var filter = Builders<MyModel>.Filter.Eq(x => x.SomeProperty == "SomeValue" && x.SomeOtherProperty == "SomeOtherValue");

    var results = collection.Find(filter).ToList();

    //Now you will have a list of MyModel objects in results - List<MyModel>
}

Once you have your collection (which ever way you go about getting it out of your database), you can just bind like this:

dgvAll.DataSource = results;
dgvAll.DataBind();