多是因爲.NET Core還不是正式版的緣故吧,MongoDB的官方Driver(http://mongodb.github.io/mongo-csharp-driver/)一直不支持.NET Core,這給想在.NET Core上嘗試MongoDB帶來了不便,本人就是其中之一 :)git
因而Fork了官方的source code,沒有太多的修改,就能夠運行了,因而打包發佈,不敢獨享!github
能夠在Nuget上搜 」RaisingStudio.MongoDB.Driver「 找到這個包,也能夠直接用Package Management Console安裝:mongodb
Install-Package RaisingStudio.MongoDB.Driver
示例:spa
using MongoDB.Bson; using MongoDB.Driver;
var client = new MongoClient("mongodb://localhost:27017"); var database = client.GetDatabase("foo"); var collection = database.GetCollection<BsonDocument>("bar"); await collection.InsertOneAsync(new BsonDocument("Name", "Jack")); var list = await collection.Find(new BsonDocument("Name", "Jack")) .ToListAsync(); foreach(var document in list) { Console.WriteLine(document["Name"]); }
或使用強類型方式:code
public class Person { public ObjectId Id { get; set; } public string Name { get; set; } }
var client = new MongoClient("mongodb://localhost:27017"); var database = client.GetDatabase("foo"); var collection = database.GetCollection<Person>("bar"); await collection.InsertOneAsync(new Person { Name = "Jack" }); var list = await collection.Find(x => x.Name == "Jack") .ToListAsync(); foreach(var person in list) { Console.WriteLine(person.Name); }
詳細說明請參見官方文檔:blog
http://mongodb.github.io/mongo-csharp-driver/文檔
源代碼:get