MongoDB is a document database designed to cater to modern application requirements. It is a scalable and a flexible solution that inherently supports distributed system design. Ballerina MongoDB Connector allows you to perform the MongoDB CRUD operations.
This module supports MongoDB version 4.2.
Before using this connector in your Ballerina application, complete the following:
Make sure a MongoDB is available to connect.
Obtain connection details such as connection URL or hostname, port number, username, and password to connect the database.
To use the
MongoDB connector in your Ballerina application, update the .bal file as follows:
Step 1: Import connector
ballerinax/mongodb module into the Ballerina project.
Step 2: Create a new connector instance
mongodb:ConnectionConfig with connection details obtained, and initialize the connector with it.
To use the MongoDB client you need to specify the database it needs to connect to. If you plan to use this client to connect to single database then you can pass the database name along with the other configurations required for client initialization(optional). Alternatively, you can pass the database name for each remote method call. This is not recommended unless you need to connect to more than one database using the client.
Step 3: Invoke connector operation
- Now you can use the operations available within the connector. Note that they are in the form of remote operations.
Following is an example on how to insert a document into a collection using the connector.
bal runcommand to compile and run the Ballerina program.