AspNetCoreMvc使用MongoDB,快来get一下吧。
看这篇文章之前请耐心看完MongoDb入门,如果还是坚持不看,那我也没有办法。
MongoDB是一个基于分布式文件存储的数据库。由C++语言编写。旨在为WEB应用提供可扩展的高性能数据存储解决方案。 它的特点是高性能、易部署、易使用,存储数据非常方便。
用之前的花,先通过nuget包get一下。
一.集成你自己的MongoDbOperation
这和我们ADO.NET,大家写的DBhelper差不多,其中只是小有变化。下面是一个helper类,我们基本上都是通过依赖注入你配置构造属性,其实的collection和db是我们最主要的配置项。
1 2 3 4 5 6 7 | private static MongoDBOperation<T> mongoDBOperation = null ; private MongoDBOperation() { mongoClient = new MongoClient( "mongodb://localhost:27017" ); db = mongoClient.GetDatabase( "local" ); collection = db.GetCollection<BsonDocument>( "zara" ); } |
通过构造函数我们完成了基本的配置,再通过泛型构造去创建我们MongoDbOperation的实例,这个实例是通过控制器方面的依赖注入进去的。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | public static MongoDBOperation<T> GetMongoDBInstance() { if (mongoDBOperation == null ) { lock (nameof(MongoDBOperation<T>)) // lockobject) { if (mongoDBOperation == null ) { mongoDBOperation = new MongoDBOperation<T>(); } } } return mongoDBOperation; } |
在控制器方面直接通过依赖注入直接Get 到了 MongoDBOperation实例。
1 2 3 4 5 | private MongoDBOperation<BsonDocument> mongo = null ; public MongoDBController() { mongo = MongoDBOperation<BsonDocument>.GetMongoDBInstance(); } |
那最后基本上就是在MongoDBOperation类中写你需要的方法了,附一份我自己写的:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 | namespace MongoDbDemo.Options { public class MongoDBOperation<T> where T : class { private static MongoDBOperation<T> mongoDBOperation = null ; private static readonly object lockobject = new object (); private MongoClient mongoClient { get ; set ; } private IMongoDatabase db { get ; set ; } private IMongoCollection<BsonDocument> collection { get ; set ; } private IEnumerable<BsonDocument> documents { get ; set ; } private MongoDBOperation() { mongoClient = new MongoClient( "mongodb://localhost:27017" ); db = mongoClient.GetDatabase( "local" ); collection = db.GetCollection<BsonDocument>( "zara" ); } public static MongoDBOperation<T> GetMongoDBInstance() { if (mongoDBOperation == null ) { lock (nameof(MongoDBOperation<T>)) // lockobject) { if (mongoDBOperation == null ) { mongoDBOperation = new MongoDBOperation<T>(); } } } return mongoDBOperation; } /// <summary> /// 同步插入数据 /// </summary> /// <param name="document"></param> /// <returns></returns> public bool InsertOneData(BsonDocument document) { try { if (collection != null ) { collection.InsertOne(document); return true ; } else { return false ; } } catch (Exception ex) { return false ; } } /// <summary> /// 异步插入 /// </summary> /// <param name="document"></param> /// <returns></returns> public async Task< bool > InsertAsyncOneData(BsonDocument document) { try { if (collection != null ) { await collection.InsertOneAsync(document); return true ; } else { return false ; } } catch (Exception ex) { return false ; } } /// <summary> /// 同步插入多条数据 /// </summary> /// <param name="documents"></param> /// <returns></returns> public bool InsertManyData(IEnumerable<BsonDocument> documents) { try { //documents = Enumerable.Range(0, 100).Select(i => new BsonDocument("counter", i)); if (collection != null ) { collection.InsertMany(documents); return true ; } else { return false ; } } catch (Exception ex) { return false ; } } /// <summary> /// 同步插入多条数据 /// </summary> /// <param name="documents"></param> /// <returns></returns> public async Task< bool > InsertAsyncManyData(IEnumerable<BsonDocument> documents) { try { //documents = Enumerable.Range(0, 100).Select(i => new BsonDocument("counter", i)); if (collection != null ) { await collection.InsertManyAsync(documents); return true ; } else { return false ; } } catch (Exception ex) { return false ; } } /// <summary> /// 查找有数据。 /// </summary> /// <returns></returns> public List<BsonDocument> FindData() { return collection.Find( new BsonDocument()).ToList(); } /// <summary> /// 取排除_id字段以外的数据。然后转换成泛型。 /// </summary> /// <returns></returns> public List<BsonDocument> FindAnsyncData() { var document = collection.Find( new BsonDocument()).ToListAsync().Result; return document; } /// <summary> /// 按某些列条件查询 /// </summary> /// <param name="bson"></param> // <returns></returns> public List<BsonDocument> FindFilterlData(BsonDocument bson) { var buildfilter = Builders<BsonDocument>.Filter; FilterDefinition<BsonDocument> filter = null ; foreach ( var bs in bson) { filter = buildfilter.Eq(bs.Name, bs.Value); } //filter = buildfilter.Eq("name", "MongoDBTest"); var documents = collection.Find(filter).ToList(); return documents; } /// <summary> /// 返回受影响行 /// </summary> /// <returns></returns> public long DeleteData() { //删除count大于0的文档。 var filter = Builders<BsonDocument>.Filter.Gt( "count" , 0); DeleteResult deleteResult = collection.DeleteMany(filter); return deleteResult.DeletedCount; } /// <summary> /// 根据id更新文档中单条数据。 /// </summary> /// <param name="_id"></param> /// <param name="bson"></param> public UpdateResult UpdateOneData( string _id, BsonDocument bson) { //修改条件(相当于sql where) FilterDefinition<BsonDocument> filter = Builders<BsonDocument>.Filter.Eq( "name" , "MongoDB" ); UpdateDefinition<BsonDocument> update = null ; foreach ( var bs in bson) { if (bs.Name.Equals( "name" )) { update = Builders<BsonDocument>.Update.Set(bs.Name, bs.Value); } } //UpdateDefinition<BsonDocument> update = Builders<BsonDocument>.Update.Set("name", bson[0].ToString()); UpdateResult result = collection.UpdateOne(filter, update); //默认更新第一条。 return result; } /// <summary> /// bsonvalue to list<string> /// </summary> public List< string > getStrListByBson(BsonValue bsonValuestr) { return bsonValuestr.ToString().Trim( '[' ).Trim( ']' ).Split( "," ).ToList(); } /// <summary> /// 根据_id删除文档行 /// </summary> public long DelDocumentById( string _id) { var filter = Builders<BsonDocument>.Filter.Eq( "_id" , new ObjectId(_id)); DeleteResult result = collection.DeleteOne(filter); return result.DeletedCount; } } } |
如果说你不知道里面的方法,你可以通通过F12去看collection中的方法(前提你是在VS的情况下)
我们再通过这玩腻去搞个小demo,控制器:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 | public class MongoDBController : Controller { private MongoDBOperation<BsonDocument> mongo = null ; public MongoDBController() { mongo = MongoDBOperation<BsonDocument>.GetMongoDBInstance(); } /// <summary> /// get首次加载 /// </summary> /// <returns>返回视图模型</returns> public IActionResult Index() { List<MongoDbModel> mdList = new List<MongoDbModel>(); if (mongo != null ) { List<BsonDocument> document = mongo.FindAnsyncData(); for ( int i = 0; i < document.Count; i++) { MongoDbModel md = new MongoDbModel() { id = document[i][ "_id" ].ToString(), title = document[i][ "title" ].ToString(), url = document[i][ "title" ].ToString(), likes = document[i][ "likes" ].ToDouble(), tags = mongo.getStrListByBson(document[i][ "tags" ]) }; mdList.Add(md); } } return View(mdList); } /// <summary> /// 查询 /// </summary> /// <param name="dbname">条件1</param> /// <returns>mongoDbList</returns> public IActionResult queryMongoDb( string dbname) { List<MongoDbModel> mdList = new List<MongoDbModel>(); if (! string .IsNullOrWhiteSpace(dbname)) { List<BsonDocument> document = mongo.FindFilterlData( new BsonDocument() { { "title" ,dbname} }); for ( int i = 0; i < document.Count; i++) { MongoDbModel md = new MongoDbModel() { id = document[i][ "_id" ].ToString(), title = document[i][ "title" ].ToString(), url = document[i][ "title" ].ToString(), likes = document[i][ "likes" ].ToDouble(), tags = mongo.getStrListByBson(document[i][ "tags" ]) }; mdList.Add(md); } } return PartialView( "MongoDbPartial" , mdList); } public long delById( string id) { return mongo.DelDocumentById(id); } |
在view中我想减小耦合度,如果是非常复杂的页面中,前提这不是MVVM,我一般喜欢把局部视图放到Shared文件夹中,其定义如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 | @model IEnumerable<MongoDbDemo.Models.MongoDbModel> <table class = "table" > <thead> <tr> <th> @Html.DisplayNameFor(model => model.id) </th> <th> @Html.DisplayNameFor(model => model.title) </th> <th> @Html.DisplayNameFor(model => model.url) </th> <th> @Html.DisplayNameFor(model => model.tags) </th> <th> @Html.DisplayNameFor(model => model.likes) </th> <th></th> </tr> </thead> <tbody> @ foreach ( var item in Model) { <tr> <td> @Html.DisplayFor(modelItem => item.id) </td> <td> @Html.DisplayFor(modelItem => item.title) </td> <td> @Html.DisplayFor(modelItem => item.url) </td> <td> @{ foreach ( var tagsItems in item.tags) { <p>@tagsItems</p> } } </td> <td> @Html.DisplayFor(modelItem => item.likes) </td> <td> @Html.ActionLink( "Delete" , "delById" , "MongoDB" , new { id = item.id}) </td> </tr> } </tbody> </table> |
主视图,直接通过 @Html.Partial 标签进行引用。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 | @model IEnumerable<MongoDbDemo.Models.MongoDbModel> @{ Layout = null ; } <script typet= "text/javascript" src= "http://libs.baidu.com/jquery/1.9.1/jquery.min.js" ></script> <!DOCTYPE html> <html> <head> <meta name= "viewport" content= "width=device-width" /> <title>Index</title> </head> <body> <form> <p> <a asp-action= "Create" >Create New</a> <div> 名称:<input type= "text" placeholder= "条件1" id= "selName" /> <input type= "button" value= "查询" id= "butn" /> </div> <div id= "datamain" > @Html.Partial( "/Views/Shared/MongoDbPartial.cshtml" , Model) </div> </p> </form> <script> $(function () { $( "#butn" ).click(function () { var nameval = $( "#selName" ).val(); alert(nameval); $.ajax({ url: "/MongoDB/queryMongoDb" , data: { dbname: nameval }, type: "get" , success: function (datas) { console.log(datas); $( "#datamain" ).html(datas); } }) }) }) </script> </body> </html> |
最后附MongoDb官方文档:https://docs.mongodb.com/
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· C#/.NET/.NET Core技术前沿周刊 | 第 29 期(2025年3.1-3.9)
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异