2

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");
}

3 Answers3

1

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);
LakshanSS
  • 126
  • 4
  • I tried this approach with the connection URL `mongodb+srv://faj-app:@fina-a-journey.ugfjnsm.mongodb.net/?retryWrites=true&w=majority`. The compilation fails with the following error. `error: 'mongodb+srv://:@fina-a-journey.ugfjnsm.mongodb.net/?retryWrites=true&w=majority' is not a valid MongoDB connection URI` – Malintha Ranasinghe Jan 17 '23 at 06:29
  • Can you able to connect that URL from any other means? Eg : MongoDB compass or VS code extension ? – Kasthuriraajan Jan 17 '23 at 09:57
0

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

0

You may try this

mongodb:ConnectionConfig mongoConfig = {
    connection: {url: "mongodb+srv://<username>:<password>@xxxxx.xxxx.mongodb.net/?retryWrites=true&w=majority"},
    databaseName: "xxxxx"
};

I have tried this in an service endpoint.

mongodb:Client mongoClient = check new (mongoConfig);
string collection = "test2";
map<json> doc = { "key1": "Value", "key2": "value2" };
check mongoClient->insert(doc, collection);