Reinvent your SQL coding with the newly released dbForge AI Assistant
Learn more

What is UniDAC

UniDAC (Universal Data Access Components) is a library of data access components developed by Devart for Delphi, C++Builder, and Lazarus. It provides a unified interface for connecting to various data sources, including MongoDB, allowing developers to create scalable, high-performance, and data-driven applications that rely on the required data storage layer.

What is UniDAC

Connect to MongoDB from Delphi via UniDAC

Prerequisites
  1. RAD Studio installed on your system
  2. UniDAC from Devart installed
  3. MongoDB connection details: server address, port number, database name, username, and password

Configure connection to MongoDB via UniDAC

  1. Start your Rad Studio.
  2. Go File > New > Windows VCL Application – Delphi to create a new Delphi project.
  1. Add the TUniConnection component.
    • 3.1 Navigate to the Component palette and find the UniDAC category.
    • 3.2 Drag and drop the TUniConnection component onto the Form Designer.
  1. Double-click the UniConnection1 label on the form, and in the dialog that opens, configure the following TUniConnection properties:
    • In the Provider dropdown menu, select MongoDB.
    • In the Server field, enter your MongoDB cluster endpoint.
    • In the Port field, enter 5439 (default MongoDB port).
    • In the Username field, enter your MongoDB username.
    • In the Password field, enter your MongoDB password.
    • In the Database field, enter the name of your MongoDB database.
    • Clear the LoginPrompt checkbox.
  2. Click Connect.

Configure connection from the Code Editor

You can use the TUniQuery or TUniTable UniDAC components to interact with MongoDB: execute SQL queries and access data. Below is an example of how to configure a connection to a MongoDB database in your code.

procedure TForm1.ConnectToMongoDB;
begin 
  UniConnection1.ProviderName := 'MongoDB';
  UniConnection1.Server := 'your-mongodb-server-address';
  UniConnection1.Port := 'your-mongodb-port';
  UniConnection1.Username := 'your-username';
  UniConnection1.Password := 'your-password';
  UniConnection1.Database := 'your-database';
  UniConnection1.LoginPrompt := False;
try
  UniConnection1.Connect;
  ShowMessage('Connection successful!');
except
  on E: Exception do
    ShowMessage('Failed to connect: ' + E.Message);
  end;
end;

You can place this code within a method that you call when your form is created or when a specific event is triggered.

Retrieve MongoDB data via UniDAC

To connect with MongoDB, UniDAC uses the MongoDB C driver, which consists of two libraries: libbson and libmongoc. To provide a seamless "out of the box" experience, UniDAC comes with these pre-built libraries for Windows. The libbson-1.0.dll and libmongoc-1.0.dll libraries are bundled with the UniDAC installation. You can find libbson-1.0.dll and libmongoc-1.0.dll in the Bin\Win32 folder (for x86) or Bin\Win64 folder (for x64), depending on your system architecture. For example, they are typically located at C:\Program Files (x86)\Devart\UniDAC for RAD Studio 12\Bin\Win32\libmongoc-1.0.dll.

Note
UniDAC supports both native MongoDB command syntax and SQL for performing CRUD operations. To enable SQL support, double-click the UniConnection1 label on the form, navigate to the Options tab, and in the SQLEngine dropdown list, select True.

To retrieve data from a MongoDB database:

  1. Add the TUniQuery and TUniDataSource components: go to the Component palette and find the UniDAC category. Then, drag and drop the components onto your form.
  2. Add the TMongoDBUniProvider component: drag and drop the TMongoDBUniProvider component onto your form from the UniDAC Providers category.
  3. Similarly, add the TButton component from the Standard category and TDBGrid from the Data Controls category.
  1. Double-click the UniQuery1 label in the Form Designer and enter a query to select the data from a database residing on MongoDB. If you have enabled the support for SQL on the Options tab of the UniQuery form, you can use SQL syntax:
SELECT * FROM employee;

UniDAC also offers limited support for MongoDB's native query language. Thus, you can use it to retrieve MongoDB data as well. For example:

{ find : employee }
  1. Click OK to save changes and close the dialog.
  1. Click the DBGrid1 label in the Form Designer and set the DataSource property to the UniDataSource1 value in the Object Inspector.
  2. Click the UniDataSource1 label in the Form Designer and set the DataSet property to the UniQuery1 value in the Object Inspector.
  3. Call the Open method in your application to execute the SQL query: double-click the Button1 label, and in the Code Editor that opens, add the following code:
UniQuery1.Open

The complete procedure code should look like this:

procedure TForm2.Button1Click(Sender: TObject);
begin
  UniQuery1.Open
end;
  1. Click Run.
  2. In the window that opens, click the button to display the result.

Manipulate MongoDB data via UniDAC

Visual data manipulation using Delphi IDE

To insert, update, or delete data visually in Rad Studio

  1. Select the TUniQuery component on the form.
  2. In the Object Inspector, locate the SQL property.
  3. Click the ellipsis (...) next to the SQL property to open the SQL editor.
  4. Enter the INSERT, UPDATE, or DELETE query into the SQL editor and click OK.
  5. Execute the query by setting the Active property of TUniQuery to True in the Object Inspector.

Data manipulation using code

MongoDB is a NoSQL database that doesn't natively support SQL for data manipulation. However, by enabling UniDAC's SQLEngine option, you can execute CRUD (Create, Read, Update, Delete) operations using standard SQL commands.

INSERT data

UniQuery1.SQL.Text := 'INSERT INTO employee (name, position, department_id) ' +
                      'VALUES (''Jordan Sanders'', ''Manager'', 1);';

UniQuery1.Execute;

You can also use the MongoDB insert command to insert documents into a collection, for example:

UniQuery1.SQL.Text := '{"insert":"employee", "documents":[{"_id":1, "name":"Jordan
Sanders", "position":"Manager", "department_id":1}]}';

UniQuery1.Execute;

UPDATE data

UniQuery1.SQL.Text := 'UPDATE employee SET position = ''Senior Manager'' WHERE name
= ''Jordan Sanders'';';

UniQuery1.Execute;

You can also use the MongoDB update command to update documents in a collection, for example:

UniQuery1.SQL.Text := '{"update":"employee", "updates":[{"q":{"name":"Jordan Sanders"},
"u":{"$set":{"position":"Senior Manager"}}}]}';

UniQuery1.Execute;

DELETE data

UniQuery1.SQL.Text := 'DELETE FROM employee WHERE name = ''Jordan Sanders'';';

UniQuery1.Execute;

You can also use the MongoDB delete command to delete documents from a collection, for example:

UniQuery1.SQL.Text := '{"delete":"employee", "deletes":[{"q":{"name":"Jordan Sanders"}}]}';

UniQuery1.Execute;

Handling MongoDB-specific features

Setting the method of describing MongoDB data

You can use the DescribeMethod property to choose between dmGrid and dmObject, depending on whether you want to work with MongoDB data in a tabular form or as complex, nested documents.

What is the DescribeMethod property in UniDAC?

The DescribeMethod property in UniDAC allows developers to choose the method of describing data when working with MongoDB collections. Its two options are dmGrid and dmObject, each suited to different data structures and use cases.

dmGrid: Work with tabular data

When the DescribeMethod property is set to dmGrid, UniDAC interprets MongoDB documents in a manner similar to traditional relational database rows. Each document in a MongoDB collection is treated as a row, and the fields within each document are treated as columns.

For example, if you have a collection where each document represents a department with fields like name, location, and budget, setting DescribeMethod to dmGrid will allow you to display this information in a grid where each department is a row, and each field is a column.

dmObject: Work with complex, nested documents

When the DescribeMethod property is set to dmObject, UniDAC maintains the hierarchical nature of MongoDB documents.For example, if your MongoDB documents include an array of employee objects within each department document, using dmObject will allow you to access and manipulate these nested arrays directly, which would be quite cumbersome in a tabular format.

How to set the DescribeMethod property in UniDAC

To set the DescribeMethod property visually

  1. Double-click the TUniQuery or TUniTable component on your form.
  2. In the form that opens, go to the Options tab.
  3. Set the DescribeMethod property by selecting either the dmGrid or dmObject option from the drop-down list.

To set the DescribeMethod property programmatically

Use the following code:

UniQuery1.SpecificOptions.Values['DescribeMethod'] := 'dmGrid'; // For tabular data representation
// or
UniQuery1.SpecificOptions.Values['DescribeMethod'] := 'dmObject'; // For hierarchical data representation

Accessing a MongoDB document

You can use the TMongoDocument class in UniDAC to access and modify MongoDB documents in the code.

What is the TMongoDocument class in UniDAC?

The TMongoDocument class in UniDAC is designed to simplify the interaction with MongoDB documents in Delphi applications. It provides a convenient way to access, manipulate, and traverse documents within a MongoDB collection

Fetch a document from MongoDB

Use TUniQuery.GetObject method to execute a query and fetch a document from MongoDB:

uses
...
MongoObjectsUni;

...
var
  Document: TMongoDocument;
begin
  UniQuery1.Open;
  Document := TMongoDocumentField(UniQuery1.Fields[0]).AsDocument;
...

Access a document as JSON

To access or modify an entire MongoDB document in JSON format, you can use the following properties and methods.

Text property

The Text property allows you to get or set the entire content of a document as a JSON string. For example:

ShowMessage(Document.AsString); // Displays the JSON content of the employee document
Document.AsString := '{"name": "Jordan Sanders", "position": "Manager", "department_id": 1}'; // Sets
the employee document content

LoadFromFile and SaveToFile methods

The LoadFromFile method loads the content of the document from a text file. The SaveToFile method saves the document’s content to a text file. For example:

Document.LoadFromFile('employee_data.txt'); // Loads employee JSON content from a
file
Document.SaveToFile('saved_employee_data.txt'); // Saves the employee document as a
JSON file

LoadFromStream and SaveToStream methods

The LoadFromStream method loads the content of an employee document from a stream. The SaveToStream method saves the employee document’s content to a stream.

Document.LoadFromStream(SomeStream); // Loads employee JSON content from a
stream
Document.SaveToStream(SomeStream); // Saves the employee document to a stream

Conclusion

Connecting Delphi to MongoDB using UniDAC provides a reliable way to manage NoSQL databases within Delphi applications. UniDAC simplifies working with MongoDB by allowing you to interact with MongoDB databases using familiar SQL queries, bridging the gap between SQL and NoSQL environments for a smoother and more efficient development experience.
By following the steps outlined in this article, you can quickly and easily integrate MongoDB into your Delphi project.