[英]How do I Connect to MongoDB Atlas cluster from Ballerina?
我一直在嘗試使用mongodb:Client
連接到 MongoDB Atlas 中的集群。 我找不到 Ballerina 客戶端支持的任何connection string
。 我找不到任何建議如何這樣做的示例代碼。
以下是源代碼
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");
}
請參考https://lib.ballerina.io/ballerinax/mongodb/4.0.0/records/ConnectionConfig
你可以試試這個:
mongodb:ConnectionConfig mongoConfig = {
connection: {
url: "xxxxx"
},
databaseName: "MyDb"
};
mongodb:Client mongoClient = check new (mongoConfig);
我傳遞給客戶端的連接字符串中的密碼有一些特殊字符,應該使用 % 進行轉義。 在 escaping 之后它起作用了。 這里指定https://www.mongodb.com/docs/atlas/troubleshoot-connection/#special-characters-in-connection-string-password
你可以試試這個
mongodb:ConnectionConfig mongoConfig = {
connection: {url: "mongodb+srv://<username>:<password>@xxxxx.xxxx.mongodb.net/?retryWrites=true&w=majority"},
databaseName: "xxxxx"
};
我在服務端點嘗試過這個。
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.