看这篇文章之前请耐心看完MongoDb入门,如果还是坚持不看,那我也没有办法。
用之前的花,先通过nuget包get一下。
一.集成你自己的MongoDbOperation
这和我们ADO.NET,大家写的DBhelper差不多,其中只是小有变化。下面是一个helper类,我们基本上都是通过依赖注入你配置构造属性,其实的collection和db是我们最主要的配置项。
private static MongoDBOperation<T> mongoDBOperation = null;
private MongoDBOperation()
{
mongoClient = new MongoClient("mongodb://localhost:27017");
db = mongoClient.GetDatabase("local");
collection = db.GetCollection<BsonDocument>("zara");
}
通过构造函数我们完成了基本的配置,再通过泛型构造去创建我们MongoDbOperation的实例,这个实例是通过控制器方面的依赖注入进去的。
public static MongoDBOperation<T> GetMongoDBInstance()
{
if (mongoDBOperation == null)
{
lock (nameof(MongoDBOperation<T>))// lockobject)
{
if (mongoDBOperation == null)
{
mongoDBOperation = new MongoDBOperation<T>();
}
}
} return mongoDBOperation;
}
在控制器方面直接通过依赖注入直接Get 到了 MongoDBOperation实例。
private MongoDBOperation<BsonDocument> mongo = null;
public MongoDBController()
{
mongo = MongoDBOperation<BsonDocument>.GetMongoDBInstance();
}
那最后基本上就是在MongoDBOperation类中写你需要的方法了,附一份我自己写的:
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,控制器:
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文件夹中,其定义如下:
@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 标签进行引用。
@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/