我正在尝试从控制台应用程序(Visual Studio C#)连接到我在运行在docker容器中的mongodb,但无法完成它。运行我的应用程序时没有出现任何错误,但是当我检查docker容器中的mongodb时,它没有显示我的应用程序的任何插入文档。
这是我尝试连接到我的mongodb的代码片段:
var client = new MongoClient("mongodb://127.0.0.1:27017");
var db = client.GetDatabase("test");
var collection = db.GetCollection<BsonDocument>("testColl");
var document = new BsonDocument {
{"Name", "h" },
{"Dep", "ADI" }
};
在我的docker Container中创建mongodb时,我觉得我做错了。我只是拉了最新的mongo图像,然后做了以下操作:docker run --name myMongoTestDb -d mongo
这里可能有一些问题:
1)确保在创建文档后在集合上调用Insert
collection.Insert(document)
2)确保使用-p
参数从容器中将27017端口暴露给localhost
docker run --name myMongoTestDb -p 27017:27017 -d mongo
更多阅读:
公开端口 - https://github.com/wsargent/docker-cheat-sheet#exposing-ports使用C#插入文档 - https://mongodb-documentation.readthedocs.io/en/latest/ecosystem/tutorial/getting-started-with-csharp-driver.html#insert-a-document
你也应该暴露27017端口。尝试
docker run --name myMongoTestDb -p 27017:27017 -d mongo