简体   繁体   English

无法将C#连接到mongoDb

[英]Can't connect c# to mongoDb

I'm trying to connect to a program coded in C# to a mongoDB. 我正在尝试将用C#编码的程序连接到mongoDB。 I have created a new collection and I have inserted some data . 我创建了一个新集合,并插入了一些数据。 I'm using mlab as host for my dataBase. 我将mlab用作数据库的主机。

MongoClientSettings settings = new MongoClientSettings();
settings.Server = new MongoServerAddress("ds145128.mlab.com", 45128);
MongoClient client = new MongoClient(settings);

var db = client.GetDatabase("unknowndb");
var coll = db.GetCollection<Book>("book");

Please help me, when I execute the program, it show me a error message that I can't connect to the DB? 请帮助我,当我执行程序时,它显示一条错误消息,提示我无法连接到数据库?

I connected like that 我这样连接

var connectionString = ConfigurationManager.ConnectionStrings[CONNECTION_STRING_NAME].ConnectionString;
var mongoUrl = new MongoUrl(connectionString);
var client = new MongoClient(mongoUrl);
var database = client.GetDatabase(mongoUrl.DatabaseName);

And my connection string like this. 和我的连接字符串是这样的。 I connected to local mongodb. 我连接到本地mongodb。 You can use MongoUrl 您可以使用MongoUrl

mongodb://[username:password@]host1[:port1][/[database][?options]] mongodb:// [用户名:密码@] host1 [:port1] [/ [数据库] [?选项]]

mongodb://localhost:27017/dbtest?readPreference=primary

Thanks a lot for you answers, this is how to connect with mongodb c# driver 2.0.1 非常感谢您的回答,这是如何与mongodb c#驱动程序2.0.1连接的方法

   static void Main(string[] args)
    {
        Task t = MainAsync(args);
        t.Wait();
    }

    static async Task MainAsync(string[] args)
    {
        var client = new MongoClient("mongodb://localhost:27017/test");
        var db = client.GetDatabase("name");
        var coll = db.GetCollection<Book>("collName");}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM