看这篇文章之前请耐心看完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. Spring基础知识备案

    关于@Value注解不能为静态变量赋值的问题 // eg:(xxx.ooo.value=100) 以下这种方式,来自配置文件的属性值无法注入: public class XxxUtils { @Val ...

  2. CMD运行命令每次都要进入很麻烦

    20:35:52 win+r  输入regedit 进入注册表 找到HKEY_LOCAL_MACHINE\Software\Microsoft\Command Processor项 创建AutoRun ...

  3. C#代码总结01---如何清空页面上所有文本框的内容。(用于录入后的清空)

    /// <summary> /// 清空页面上所有TextBox的内容.用于录入后的清空 /// </summary> /// <param name="top ...

  4. Win Server 2003 10条小技巧

    微软推出Windows Server 2003已经有一段时间了,但是,由于它是一个面向企业用户的服务器操作系统,所以,没有引起更多个人用户的注意.实际上,简单地改变一下系统的设置,您也可以将Windo ...

  5. PBRT笔记(6)——采样和重构

    前言 本文仅作为个人笔记分享,又因为本章涉及多个专业领域而本人皆未接触过,所以难免出错,请各位读者注意. 对于数字图像需要区分image pixels(特定采样处的函数值)和display pixel ...

  6. 20162329张旭升 2018-2019-2《网络对抗技术》第1周 Kali的安装

    目录 Kali的安装 设置与主机的文件交互 Kali的安装 1.创建虚拟机 2.选择安装语言 3.设置网络 4.设置分区 5.安装完成 设置与主机的文件交互 首先在vmware workstation ...

  7. 关于resharper激活

    resharper 是一款非常强大的vs辅助开发插件,提供了很多快捷操作功能,本人已经离不开它了,但是resharper总会遇到lincese过期,需要激活的问题,现在提供以下方式,仅供参考 1.打开 ...

  8. SpringBoot整合使用JdbcTemplate

    JdbcTemplate是Spring框架自带的对JDBC操作的封装,目的是提供统一的模板方法使对数据库的操作更加方便.友好,效率也不错. 整合使用JdbcTemplate实现对图书的添加功能小案例 ...

  9. NOIP-珠心算

    题目描述 珠心算是一种通过在脑中模拟算盘变化来完成快速运算的一种计算技术.珠心算训练,既能够开发智力,又能够为日常生活带来很多便利,因而在很多学校得到普及. 某学校的珠心算老师采用一种快速考察珠心算加 ...

  10. 关于外网无法访问阿里云主机CentOs

    前两天阿里云ECS搞活动,所有买了个三年的Ecs,然后照着之前在虚拟机同样的搭建服务器,一切都很正常,可是 当我配置好防火墙和nginx之后,发现个问题,外网无法访问. 思考: 1.我的nginx没配 ...