UniDAC

Using MongoDB data access provider with UniDAC in Delphi

This article provides a brief overview of the MongoDB data access provider for UniDAC used to establish a connection to MongoDB from Delphi and Lazarus. You will find the description of some useful features and how to get started quickly.

Overview

The main features of MongoDB data access provider are:

The full list of MongoDB provider features can be found in Features page.

Both Professional and Standard editions of UniDAC include the MongoDB provider. Express Edition of UniDAC does not include the MongoDB provider.

Compatibility

To learn the supported MongoDB versions and clients, refer to the Compatibility section.

Requirements

Applications that use the MongoDB provider require libmongoc and libbson client libraries. The MongoDB provider dynamically loads client libraries (for example, libmongoc-1.0.dll and libbson-1.0.dll on Windows) available on user system. To locate DLLs you can set ClientLibrary and BSONLibrary specific options of TUniConnection respectively with paths to client libraries. By default, the MongoDB provider searches for client libraries in the directories specified in the PATH environment variable.

In addition to the standard client libraries, you can use the ones distributed with UniDAC. 32-bit libraries are located in the 'Bin\Win32\' subfolder relative to the folder where UniDAC was installed. 64-bit ones in the 'Bin\Win64\' subfolder. For example:

  UniConnection1.SpecificOptions.Values['MongoDB.BSONLibrary'] := 'C:\Program Files (x86)\Devart\UniDAC for RAD Studio 10.3\Bin\Win32\libbson-1.0.dll';
  UniConnection1.SpecificOptions.Values['MongoDB.ClientLibrary'] := 'C:\Program Files (x86)\Devart\UniDAC for RAD Studio 10.3\Bin\Win32\libmongoc-1.0.dll';
  UniConnection1.Connect;

Deployment

When an application was built without runtime packages (Link with runtime packages set to False in Project Options), you do not need to deploy any BPL files with it. For more information, see Deployment.
Note that UniDAC Trial requires deployment of additional BPL files regardless of Link with runtime packages.

MongoDB-specific options

Though UniDAC is a library of components that provide unified interface to work with different database servers, it also lets you tune behaviour for each server individually. For thin setup of a certain database server, UniDAC provides server-specific options. These options can be applied to such components as TUniConnection, TUniQuery and TUniTable via their SpecificOptions property. SpecificOptions is a string list. Therefore you can use the following syntax to assign an option value:

  TUniConnection.SpecificOptions.Values['UseUnicode'] := 'True';

Below you will find the description of allowed options grouped by components.

TUniConnection

Option name Description
AdditionalServers Specifies additional servers to connect to, separated by commas. Each server has to be specified in the host[:port] format as it is described in the official MongoDB documentation.
BSONLibrary Use the BSONLibrary option to set or get the libbson client library location.
ClientLibrary Use the ClientLibrary option to set or get the libmongoc client library location.
ConnectionOptions Connection specific options. See official MongoDB documentation for a full description of these options.
LowerCaseObjectID Use the option to return ObjectId values in lower case. The default value is False.
SQLEngine If set to True, the driver will use the SQL language to access data in a MongoDB database, otherwise it will use the standard Mongo query language. The default value is False.
UseUnicode Enables or disables Unicode support. Affects on the character data fetched from the server. When set to True all character data is stored as WideStrings, and TStringField is replaced with TWideStringFiled.

TUniQuery, TUniTable

Option name Description
AllowAddField If True, then when editing an existing document, it allows to add new fields to the document. If False, an attempt to add a new field to the document will raise an exceptin. For newly created documents adding new fields is always allowed. The default value is True.
AllowChangeType If True, when editing an existing document, it allows to assign a value of another type to the existing document field. If False, an attempt to assign a value of another type will raise an exceptin. For newly created documents changing field type is always allowed. The default value is True.
ComplexAsString If True, then complex fields of a document (which are of object, array, timestamp, binary, regular expression or JavaScript type) are mapped as TStringField and their content is displayed in the Extended JSON format. If False, such fields are mapped as TADTField with its child fields. The default value is False.
DescribeMethod Defines a way of creating dataset fields.
The following values are allowed for this property:

dmGrid
The field list is generated based on a sample of DescribeAmont documents. The list includes all unique fields from all documents in the sample.
dmObject
The dataset has a single field of the ftADT type, which provides access to the entire document.


The default value is dmGrid.
DescribeAmount Specifies the number of sample documents used to create a list of fields in the dataset when DescribeMethod is set to dmGrid. The default value is 25.
FetchAll If True, all records of the query are requested from database server when the dataset is being opened. If False, records are retrieved when a data-aware component or a program requests it. The default value is False.

Note: Since parametrized commands are not supported in MongoDB, the MongoDB provider does not support parameters. Also, update SQL-s are not supported too.

TUniSQL

The TUniSQL component has no MongoDB-specific options.

TUniStoredProc, TUniScript, TUniDump, TUniLoader, TUniTransaction

TUniStoredProc, TUniScript, TUniDump, TUniLoader and TUniTransaction components are not supported for the MongoDB provider.

MongoDB-specific notes

This chapter describes several special cases of using the MongoDB provider.

Data types

The MongoDB provider supports the following MongoDB data types:


By default, document fields of these types are mapped in a dataset as follows:

Query and update operations

Since MongoDB is a No-SQL database, the MongoDB provider does not support regular SQL to manage documents. Instead, it supports native MongoDB command syntax to perform CRUD operations:

Accessing a document using the TMongoDocument class

To access and modify a document in the code, you can use a special TMongoDocument class that has a set of properties and methods for working with the document structure. The data set always contains at least one field of the ftADT type, which has the same name as the collection and provides access to the entire document using the TMongoDocument class.

Obtaining a document

To obtain an existing document instance, use the TUniQuery.GetObject method:
uses
...
  MongoObjectsUni;
...
var
  Document: TMongoDocument;
begin
  UniQuery1.Edit;
  Document := UniQuery1.GetObject('restaurants') as TMongoDocument;
...
Or, for a newly created document:
uses
...
  MongoObjectsUni;
...
var
  Document: TMongoDocument;
begin
  UniQuery1.Append;
  Document := UniQuery1.GetObject('restaurants') as TMongoDocument;
...

Accessing a document as JSON

To access / change the entire document in the JSON format, use the following properties and methods:

Accessing the document fields

To iterate through the document fields use FieldCount and Fields property. To access the field value use its Name property. To access the field value use its Value property. For fields of complex data types the return value contains the JSON representation of the field. Example:
for i := 0 to Document.FieldCount - 1 do
  ShowMessage(Document.Fields[i].Name + ': ' + Document.Fields[i].Value);
Also, you can access the particular field of the document via its name using the FieldByName property, for example:
ShowMessage(Document.FieldByName['name'].Value);
or
ShowMessage(Document['name'].Value);

Modifying a document using the "fluent" interface

The TMongoDocument class provides a set of SetXX methods which allow to easily change its structure. Methods can be combined one by one into a chain, thus making it easier to write code.

Data Type Mapping

The following table lists the constants for mapping MongoDB data types to Delphi data types. See Data Type Mapping for more information.

Constant Description
mongoString Maps String to Delphi data types.
mongoNumber Maps Number to Delphi data types.
mongoBoolean Maps Boolean to Delphi data types.
mongoObject Maps Object to Delphi data types.
mongoArray Maps Array to Delphi data types.
mongoNull Maps Null to Delphi data types.
mongoObjectId Maps ObjectId to Delphi data types.
mongoInt32 Maps 32-bit integer to Delphi data types.
mongoInt64 Maps 64-bit integer to Delphi data types.
mongoDouble Maps Double to Delphi data types.
mongoDateTime Maps DateTime to Delphi data types.
mongoTimestamp Maps Timestamp to Delphi data types.
mongoUndefined Maps Undefined to Delphi data types.
mongoBinary Maps Binary data to Delphi data types.
mongoRegex Maps Regular Expression to Delphi data types.
mongoJavaspan Maps Javascript span to Delphi data types.
mongoJavaScopespan Maps JavaScript span with scope to Delphi data types.
mongoMinKey Maps Min key to Delphi data types.
mongoMaxKey Maps Max key to Delphi data types.
mongoDBPointer Maps DBPointer to Delphi data types.
mongoDecimal128 Maps Decimal128 to Delphi data types.
© 1997-2024 Devart. All Rights Reserved. Request Support DAC Forum Provide Feedback