看这篇文章之前请耐心看完MongoDb入门,如果还是坚持不看,那我也没有办法。

MongoDB是一个基于分布式文件存储的数据库。由C++语言编写。旨在为WEB应用提供可扩展的高性能数据存储解决方案。 它的特点是高性能、易部署、易使用,存储数据非常方便。

用之前的花,先通过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/

AspNetCoreMvc使用MongoDB,快来get一下吧。的更多相关文章

  1. MongoDB:逐渐变得无关紧要

    我与MongoDB的关系可分为三个阶段.对于目前处于第三阶段的我来说,这款产品似乎变得无关紧要了.很快你就会明白为什么我这么说. 阶段一:痴迷 我与MongoDB的第一次接触十分神奇:一个poligl ...

  2. MongoDB设计系列

    原创文章,如果转载请标明出处.作者. https://www.cnblogs.com/alunchen/p/9762233.html 1 前言 MongoDB作为现今流行的非关系型文档数据库,已经有很 ...

  3. 同等条件下,mongo为什么比mysql快?

    写操作MongoDB比传统数据库快的根本原因是Mongo使用的内存映射技术 - 写入数据时候只要在内存里完成就可以返回给应用程序,这样并发量自然就很高.而保存到硬体的操作则在后台异步完成. 读操作Mo ...

  4. mongodb研究(mongodb 内存数据库)

    本日志大部分都不是原创的转载复制的会带链接保持版权 工作中使用mongodb已经好久了,讽刺的是到了最后快离职的时候才有时间好好研究下源码.   印象:mongodb是一个内存数据库,数据都是放到内存 ...

  5. redis,缓存雪崩,粗粒度锁,缓存一致性

    1, redis单线程为什么快 io多路复用技术 单线程避免多线程的频繁切换问题 memcache缺点 kv形式数据 没有持久化mongodb 海量数据的访问效率 mr的计算模型文档就是类似json的 ...

  6. MongoDB--副本集基本信息【面试必备】

    副本集的概念 副本集是一组服务器,其中有一个是主服务器(primary),用于处理客户端请求:还有多个备份服务器(secondary),用于保存主服务器的数据副本.如果主服务器崩溃了,备份服务器会自动 ...

  7. 【SQL Server性能优化】运用SQL Server的全文检索来提高模糊匹配的效率

    原文:[SQL Server性能优化]运用SQL Server的全文检索来提高模糊匹配的效率 今天去面试,这个公司的业务需要模糊查询数据,之前他们通过mongodb来存储数据,但他们说会有丢数据的问题 ...

  8. MongoDB--副本集基本信息

    副本集的概念 副本集是一组服务器,其中有一个是主服务器(primary),用于处理客户端请求:还有多个备份服务器(secondary),用于保存主服务器的数据副本.如果主服务器崩溃了,备份服务器会自动 ...

  9. MongoDB 分片管理(四)数据均衡 -- 特大快

    1.1 特大快形成 如果用date字段作为片键,集合中date是一个日期字符串,如:year/month/day,也就是说,mongoDB一天创建一个块.因块内所有文档的片键一样,因此这些块是不可拆分 ...

随机推荐

  1. Java基础知识总结(超级经典)

    Java基础知识总结(超级经典) 写代码: 1,明确需求.我要做什么? 2,分析思路.我要怎么做?1,2,3. 3,确定步骤.每一个思路部分用到哪些语句,方法,和对象. 4,代码实现.用具体的java ...

  2. 展开被 SpringBoot 玩的日子 《 四 》 Session 会话共享

    共享Session-spring-session-data-redis 分布式系统中,sessiong共享有很多的解决方案,其中托管到缓存中应该是最常用的方案之一. Spring Session官方说 ...

  3. BZOJ.2054.疯狂的馒头(并查集)

    BZOJ 倒序处理,就是并查集傻题了.. 并查集就是确定下一个未染色位置的,直接跳到那个位置染.然而我越想越麻烦=-= 以为有线性的做法,发现还是要并查集.. 数据随机线段树也能过去. //18400 ...

  4. vue插件官方文档,做个记录

    vue的插件,组件都可以按照这种方式添加 官方文档 https://cn.vuejs.org/v2/guide/plugins.html 做个记录用

  5. FTP连接虚拟主机响应220 Welcome to www.net.cn FTP service. (解决的一个问题)

    问题场景: 使用FTP客户端连接虚拟主机时,同样的账号密码在有的网络下可以连接成功,有的网络下却一直连接不上:ftp响应“220 Welcome to www.net.cn FTP service.” ...

  6. jquery 点击事件切换样式

    $('#FatherName').on('click', '.ClassName', function(e){ $('.ClassName').removeClass('active'); $(thi ...

  7. mybatis 之数据库 include refid ="base_column_list"

    mybatis 之数据库 include refid ="base_column_list" 对于刚学习使用SSM框架的新手来说,mybatis中的数据库语句有点不一样,下面便是对 ...

  8. svn idea 修改文件,文件不变色

    删除后,重新添加. 我这里是什么也没有选择,选上Subversion后,保存,再修改文件,文件颜色就变了 Settings-->Version Control

  9. XP .Net 4.0使用Microsoft.Bcl需要安装XP补丁NDP40-KB2468871-v2-x86

    XP .Net 4.0使用Microsoft.Bcl需要安装XP补丁NDP40-KB2468871-v2-x86

  10. 使用getline输入一行字符串

    给定10个国家名,按字母顺序输出,国家名中可以包含空格,国家名用换行隔开 #include<algorithm> #include<iostream> #include< ...