在.Net中使用Mongo核心web api
问题描述:
我有一个可用的Mongo和.Net Core应用程序,但仍然需要通过C#访问mongo数据库。我只是通过尝试在program.cs文件中进行连接来测试这一点。在顶部,我有:在.Net中使用Mongo核心web api
using MongoDB.Driver;
using MongoDB.Driver.Core;
using MongoDB.Bson;
当我运行:
var mongo = new MongoClient("mongodb://localhost:27017");
var db = mongo.GetDatabase("cvpz");
mongo.getCollection("people");
我得到这个错误:
Program.cs(16,19): error CS1061: 'MongoClient' does not contain a definition for 'getCollection' and no extension method 'getCollection' accepting a first argument of type 'MongoClient' could be found (are you missing a using directive or an assembly reference?) [/src/src/Identity.api/Identity.api.csproj]
现在,我可以通过命令行通过“蒙戈本地主机访问DB/cvpz”。顺便说一句,我使用Ubuntu来运行.Net Core。
当我运行createCollection()时,我得到一个类似的错误。我如何使用C#与Mongo交互?
最后一件事,我应该有所有必需的包,我有这些在我的.csproj:
<PackageReference Include="MongoDB.Driver" Version="2.3.0" />
<PackageReference Include="MongoDB.Driver.Core" Version="2.3.0" />
<PackageReference Include="MongoDB.Bson" Version="2.3.0" />
非常感谢你们!
答
两件事。 'GetCollection'应该有一个大写字母G.它还需要一个通用参数来指示存储的文档类型。对于您例如:
var mongo = new MongoClient("mongodb://localhost:27017");
var db = mongo.GetDatabase("cvpz");
var coll = mongo.GetCollection<People>("people");
我是否需要将其添加到该文件的.csproj?或者说是'使用IMongoDatabase.GetCollection'?另外,我是否需要为每个要使用的命令获取使用语句? – Coder
@Joel将什么添加到csproj文件?从这个问题和你在15个小时前问的问题,你有正确的参考。 “参考:IMongoDatabase.GetCollection”是文档的链接。 –
哈哈抱歉,一直在盯着电脑屏幕。谢谢你的帮助! :) – Coder