看这篇文章之前请耐心看完MongoDb入门,如果还是坚持不看,那我也没有办法。
MongoDB是一个基于分布式文件存储的数据库。由C++语言编写。旨在为WEB应用提供可扩展的高性能数据存储解决方案。 它的特点是高性能、易部署、易使用,存储数据非常方便。
用之前的花,先通过nuget包get一下。
一.集成你自己的MongoDbOperation
这和我们ADO.NET,大家写的DBhelper差不多,其中只是小有变化。下面是一个helper类,我们基本上都是通过依赖注入你配置构造属性,其实的collection和db是我们最主要的配置项。
private static MongoDBOperation mongoDBOperation = null;
private MongoDBOperation()
{
mongoClient = new MongoClient("mongodb://localhost:27017");
db = mongoClient.GetDatabase("local");
collection = db.GetCollection("zara");
}
通过构造函数我们完成了基本的配置,再通过泛型构造去创建我们MongoDbOperation的实例,这个实例是通过控制器方面的依赖注入进去的。
public static MongoDBOperation GetMongoDBInstance()
{
if (mongoDBOperation == null)
{
lock (nameof(MongoDBOperation))// lockobject)
{
if (mongoDBOperation == null)
{
mongoDBOperation = new MongoDBOperation();
}
}
}
return mongoDBOperation;
}
在控制器方面直接通过依赖注入直接Get 到了 MongoDBOperation实例。
private MongoDBOperation mongo = null;
public MongoDBController()
{
mongo = MongoDBOperation.GetMongoDBInstance();
}
那最后基本上就是在MongoDBOperation类中写你需要的方法了,附一份我自己写的:
namespace MongoDbDemo.Options { public class MongoDBOperationwhere T : class { private static MongoDBOperation mongoDBOperation = null; private static readonly object lockobject = new object(); private MongoClient mongoClient { get; set; } private IMongoDatabase db { get; set; } private IMongoCollection collection { get; set; } private IEnumerable documents { get; set; } private MongoDBOperation() { mongoClient = new MongoClient("mongodb://localhost:27017"); db = mongoClient.GetDatabase("local"); collection = db.GetCollection ("zara"); } public static MongoDBOperation GetMongoDBInstance() { if (mongoDBOperation == null) { lock (nameof(MongoDBOperation ))// lockobject) { if (mongoDBOperation == null) { mongoDBOperation = new MongoDBOperation (); } } } return mongoDBOperation; } /// /// 同步插入数据 /// /// ///public bool InsertOneData(BsonDocument document) { try { if (collection != null) { collection.InsertOne(document); return true; } else { return false; } } catch (Exception ex) { return false; } } /// /// 异步插入 /// /// ///public async Task InsertAsyncOneData(BsonDocument document) { try { if (collection != null) { await collection.InsertOneAsync(document); return true; } else { return false; } } catch (Exception ex) { return false; } } /// /// 同步插入多条数据 /// /// ///public bool InsertManyData(IEnumerable 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; } } /// /// 同步插入多条数据 /// /// ///public async Task InsertAsyncManyData(IEnumerable 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; } } /// /// 查找有数据。 /// ///public List FindData() { return collection.Find(new BsonDocument()).ToList(); } /// /// 取排除_id字段以外的数据。然后转换成泛型。 /// ///public List FindAnsyncData() { var document = collection.Find(new BsonDocument()).ToListAsync().Result; return document; } /// /// 按某些列条件查询 /// /// //public List FindFilterlData(BsonDocument bson) { var buildfilter = Builders .Filter; FilterDefinition 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; } /// /// 返回受影响行 /// ///public long DeleteData() { //删除count大于0的文档。 var filter = Builders .Filter.Gt("count", 0); DeleteResult deleteResult = collection.DeleteMany(filter); return deleteResult.DeletedCount; } /// /// 根据id更新文档中单条数据。 /// /// /// public UpdateResult UpdateOneData(string _id, BsonDocument bson) { //修改条件(相当于sql where) FilterDefinitionfilter = Builders .Filter.Eq("name", "MongoDB"); UpdateDefinition update = null; foreach (var bs in bson) { if (bs.Name.Equals("name")) { update = Builders .Update.Set(bs.Name, bs.Value); } } //UpdateDefinition update = Builders .Update.Set("name", bson[0].ToString()); UpdateResult result = collection.UpdateOne(filter, update);//默认更新第一条。 return result; } /// /// bsonvalue to list public List/// getStrListByBson(BsonValue bsonValuestr) { return bsonValuestr.ToString().Trim('[').Trim(']').Split(",").ToList(); } /// /// 根据_id删除文档行 /// public long DelDocumentById(string _id) { var filter = Builders.Filter.Eq("_id", new ObjectId(_id)); DeleteResult result = collection.DeleteOne(filter); return result.DeletedCount; } } }
如果说你不知道里面的方法,你可以通通过F12去看collection中的方法(前提你是在VS的情况下)
我们再通过这玩腻去搞个小demo,控制器:
public class MongoDBController : Controller { private MongoDBOperationmongo = null; public MongoDBController() { mongo = MongoDBOperation .GetMongoDBInstance(); } /// /// get首次加载 /// ///返回视图模型 public IActionResult Index() { ListmdList = new List (); if (mongo != null) { List 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); } /// /// 查询 /// /// 条件1 ///mongoDbList public IActionResult queryMongoDb(string dbname) { ListmdList = new List (); if (!string.IsNullOrWhiteSpace(dbname)) { List 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文件夹中,其定义如下:
@model IEnumerable
@foreach (var item in Model) { @Html.DisplayNameFor(model => model.id) @Html.DisplayNameFor(model => model.title) @Html.DisplayNameFor(model => model.url) @Html.DisplayNameFor(model => model.tags) @Html.DisplayNameFor(model => model.likes) } @Html.DisplayFor(modelItem => item.id) @Html.DisplayFor(modelItem => item.title) @Html.DisplayFor(modelItem => item.url) @{ foreach (var tagsItems in item.tags) { @tagsItems
} }@Html.DisplayFor(modelItem => item.likes) @Html.ActionLink("Delete", "delById", "MongoDB",new { id = item.id})
主视图,直接通过 @Html.Partial 标签进行引用。
@model IEnumerable@{ Layout = null; } Index
最后附MongoDb官方文档:https://docs.mongodb.com/