skip to Main Content

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

Answers


  1. Chosen as BEST ANSWER

    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


  2. 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);
    
    Login or Signup to reply.
  3. 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);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search