Home > Net >  How do I Connect to MongoDB Atlas cluster from Ballerina?
How do I Connect to MongoDB Atlas cluster from Ballerina?

Time:01-18

I have been trying to connect to a cluster in MongoDB Atlas using the mongodb:Client. I am not able to find any connection string that is supported by the Ballerina client. I could not find any sample code that suggests how to do so.

Following is the source code

import ballerinax/mongodb;

configurable string app = ?;
configurable string pwd = ?;

mongodb:Client mongoCli = check new ({connection: {url: string `mongodb srv://${app}:${pwd}@fina-a-journey.ugfjnsm.mongodb.net/?retryWrites=true&w=majority`}});

public function main() {
    mongodb:Error? insert = mongoCli->insert({name: "Jhon", age: 16}, "users");
}

CodePudding user response:

Please refer to https://lib.ballerina.io/ballerinax/mongodb/4.0.0/records/ConnectionConfig

You may try this:

mongodb:ConnectionConfig mongoConfig = {
    connection: {
        url: "xxxxx"
    },
    databaseName: "MyDb"
};
mongodb:Client mongoClient = check new (mongoConfig);

CodePudding user response:

The password in the connection string that I had passed to the Client had some special characters that should be escaped using %. After escaping it worked. It is specified here https://www.mongodb.com/docs/atlas/troubleshoot-connection/#special-characters-in-connection-string-password

  • Related