.net 操作MongoDB 基础
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.Helper 13 { 14 public static class MongoDBHelper 15 { 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<Model.UserInfo>("user");//获取需要操作的集合 22 collects.InsertOne(user); 23 } 24 25 public static List<UserInfo> FindAll() 26 { 27 List<UserInfo> lis = new List<UserInfo>(); 28 var collects = db.GetCollection<UserInfo>("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 /// <summary> 44 /// 上传图片 45 /// </summary> 46 /// <param name="name"></param> 47 /// <param name="source"></param> 48 /// <returns></returns> 49 public static ObjectId UploadImg(string name, byte[] source) 50 { 51 var bucket = new GridFSBucket(db);//初始化GridFS 52 return bucket.UploadFromBytes(name, source); 53 } 54 /// <summary> 55 /// 上传图片 56 /// </summary> 57 /// <param name="name"></param> 58 /// <param name="source"></param> 59 /// <returns></returns> 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<ObjectId> UploadImgAsync(string name, Stream source) 67 { 68 var bucket = new GridFSBucket(db); 69 return await bucket.UploadFromStreamAsync(name, source); 70 } 71 /// <summary> 72 /// 查询图片 73 /// </summary> 74 /// <param name="id"></param> 75 /// <returns></returns> 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 /// <summary> 84 /// 查询图片 85 /// </summary> 86 /// <param name="id"></param> 87 /// <returns></returns> 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 }