[英]How do I Connect to MongoDB Atlas cluster from Ballerina?
I have been trying to connect to a cluster in MongoDB Atlas using the mongodb:Client
.我一直在尝试使用
mongodb:Client
连接到 MongoDB Atlas 中的集群。 I am not able to find any connection string
that is supported by the Ballerina client.我找不到 Ballerina 客户端支持的任何
connection string
。 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");
}
Please refer to https://lib.ballerina.io/ballerinax/mongodb/4.0.0/records/ConnectionConfig请参考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);
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.
在 escaping 之后它起作用了。 It is specified here https://www.mongodb.com/docs/atlas/troubleshoot-connection/#special-characters-in-connection-string-password
这里指定https://www.mongodb.com/docs/atlas/troubleshoot-connection/#special-characters-in-connection-string-password
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.