1. 下载驱动,最好使用 NuGet 下载,直接搜索MongoDB;
2. 引用相关驱动
3. 部分测试代码,主要是针对MongoDB的GridFS 文件存储来用
1 using Mongo.Model; 2 using MongoDB.Bson; 3 using MongoDB.Driver; 4 using MongoDB.Driver.GridFS; 5 using System; 6 using System.Collections.Generic; 7 using System.IO; 8 using System.Linq; 9 using System.Threading.Tasks;10 using System.Web;11 12 namespace Mongo.Helper13 {14 public static class MongoDBHelper15 {16 17 public static MongoClient client = new MongoClient("mongodb://localhost:27017"); 18 public static IMongoDatabase db = client.GetDatabase("dzdaTest");//获取需要操作数据库19 public static void Add(Model.UserInfo user)20 {21 var collects = db.GetCollection("user");//获取需要操作的集合22 collects.InsertOne(user);23 }24 25 public static List FindAll()26 {27 List lis = new List ();28 var collects = db.GetCollection ("user");29 var filter = new BsonDocument();30 using(var cursor = collects.Find(filter).ToCursor())//查询结果转化为类似游标的类型31 {32 while (cursor.MoveNext())33 {34 foreach (UserInfo item in cursor.Current)35 {36 lis.Add(item);37 }38 }39 }40 return lis;41 }42 43 /// 44 /// 上传图片45 /// 46 /// 47 /// 48 ///49 public static ObjectId UploadImg(string name, byte[] source)50 {51 var bucket = new GridFSBucket(db);//初始化GridFS52 return bucket.UploadFromBytes(name, source);53 }54 /// 55 /// 上传图片56 /// 57 /// 58 /// 59 ///60 public static ObjectId UploadImg(string name, Stream source)61 {62 var bucket = new GridFSBucket(db);63 return bucket.UploadFromStream(name, source);64 }65 66 public async static Task UploadImgAsync(string name, Stream source)67 {68 var bucket = new GridFSBucket(db);69 return await bucket.UploadFromStreamAsync(name, source);70 }71 /// 72 /// 查询图片73 /// 74 /// 75 ///76 public static Stream FindImg(string id)77 {78 var bucket = new GridFSBucket(db);79 ObjectId objId= new ObjectId(id);//通过ObjectId查询图片80 return bucket.OpenDownloadStream(objId);81 }82 83 /// 84 /// 查询图片85 /// 86 /// 87 ///88 public static byte[] FindImgWithByte(string id)89 {90 var bucket = new GridFSBucket(db);91 ObjectId objId = new ObjectId(id);92 return bucket.DownloadAsBytes(objId);93 }94 }95 }