Skip to main content
All docs
V24.1

Bind to MongoDB Data

  • 3 minutes to read

MongoDB is a general purpose, document-based, distributed database built for modern application developers and for the cloud era. It stores data in JSON-like documents.

Data Source Configuration Wizard

To bind a DevExpress data-aware control at design time, do the following.

  1. Invoke the Data Source Configuration Wizard for this control.

  2. Go to the “MongoDB Data Connection” tab and click “New Data Source…”. This button adds a new MongoDBDataSource component on the form.

MongoDB page in DevExpress Data Source Configuration Wizard

  1. Install the .NET Driver for MongoDB (NuGet Feed | GitHub releases page | GitHub repository) or let the wizard download and install it.

Install MDB driver

  1. Specify connection settings. You can either enter connection fields individually, or paste a single connection string.

Connection settings

  1. Choose databases and collections stored on your cluster. You can use our Filter Editor tool to build optional filter expressions.

Create queries

  1. Rebuild your project and re-start Data Source Configuration Wizard. You can now select your component in the “MongoDB Data Connection” tab. Choose whether you want to use the BindingSource component or bind to data directly, and specify the data source to which you wish to connect.

Select queries

Bind to MongoDB Data in Code

To bind a DevExpress data-aware control in code, you need to create and set up the MongoDBDataSource component.

Database and data collection names are stored in objects of the MongoDBQuery class, and a connection string is stored in a MongoDBCustomConnectionParameters object. See this link for information about connection string syntax: Connection String URI Format.

using DevExpress.DataAccess.ConnectionParameters;
using DevExpress.DataAccess.MongoDB;

public void InitMdbComponent() {
    // connection parameters
    MongoDBCustomConnectionParameters mongoDBCustomConnectionParameters1 =
        new MongoDBCustomConnectionParameters();
    mongoDBCustomConnectionParameters1.ConnectionString =
        "mongodb+srv://[username:password@]host1[:port1][,...hostN[:portN]][/[defaultauthdb][?options]]";
    mongoDBDataSource1.ConnectionParameters = mongoDBCustomConnectionParameters1;
    // queries
    MongoDBQuery mongoDBQuery1 = new MongoDBQuery();
    mongoDBDataSource1.ConnectionName = "MdbConnection";
    mongoDBQuery1.ActualName = "restaurants";
    mongoDBQuery1.CollectionName = "restaurants";
    mongoDBQuery1.DatabaseName = "sample_restaurants";
    mongoDBDataSource1.Queries.Add(mongoDBQuery1);
    // load data
    mongoDBDataSource1.Fill();
}

Once the component is ready, use the data-aware control’s API to connect it to your control. The code below illustrates how to bind the Data Grid to MongoDB data.

void OnFormLoad(object sender, EventArgs e) {
    gridControl1.DataMember = "restaurants";
    gridControl1.DataSource = mongoDBDataSource1;
}