Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB and C# datasource

I am using MongoDB with C# driver. I managed to add/delete/update data from collections, but I dont know how to display a collection in the gridview. If it's not possible, how can I display collections as tables in asp.net?

like image 342
Stewie Griffin Avatar asked Feb 27 '23 02:02

Stewie Griffin


1 Answers

First load a query from mongodb like this:

      var server = MongoServer.Create("mongodb://localhost:27020");
      var database = server.GetDatabase("someDb");

      var collection = database.GetCollection<User>("someCollection");
      var searchQuery = Query.EQ("someName", "someValue"); // you can place any search condition here 
      //if you want all documents from collection use FindAll
      var cursor = collection.Find(searchQuery);
      cursor.SetLimit(50); // you can specify limit
      // set sort orders
    cursor.SetSortOrder(SortBy.Ascending("someSorField").Descending("someSorField2"));

    var resultList = cursor.ToList(); //get list of items from mongodb

Then on Page_Load event, bind data:

 gvwExample.DataSource = resultList;
 gvwExample.DataBind();

Then specify binding to datasource on the page:

<asp:GridView ID="gvwExample" runat="server" AutoGenerateColumns="False" CssClass="basix" >
<columns>
 <asp:BoundField DataField="FirstName" HeaderText="First Name" />
 <asp:BoundField DataField="LastName" HeaderText="Last Name" />
</columns>
</asp:GridView> 
like image 198
Andrew Orsich Avatar answered Mar 08 '23 05:03

Andrew Orsich