看这篇文章之前请耐心看完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. 并发编程 futuretask

    package com.mrbird.api.demoThread.future; import java.util.concurrent.Callable; import java.util.con ...

  2. Nastya Is Buying Lunch

    At the big break Nastya came to the school dining room. There are nn pupils in the school, numbered ...

  3. BandwagonHost

    https://kiwivm.64clouds.com/main-exec.php?mode=extras_shadowsocks https://kiwivm.64clouds.com/main-e ...

  4. Android常规布局方式和方法

    一.关于给控件添加ID属性 <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xm ...

  5. BZOJ 4710

    枚举几个同学分到了 对于每种特产求一个方案数(经典做法)乘起来 然后容斥 #include<bits/stdc++.h> using namespace std; #define rep( ...

  6. 制作docker-jdk7-zookeeper镜像(非集群版)

    ## 准备工作 用到的工具, Xshell5, Xftp5, jdk-7u79-linux-x64.tar.gz, zookeeper-3.4.9.tar.gz, docker.io/centos:l ...

  7. 201771010126 王燕《面向对象程序设计(Java)》第十三周学习总结

    实验十三  图形界面事件处理技术 实验时间 2018-11-22 1.实验目的与要求 (1) 掌握事件处理的基本原理,理解其用途: 事件源 (eventevent eventeventsource s ...

  8. Summer Project

    Summer Project Summer是一个用于学习交流,基于Netty4.x的简单mvc库. 使用 快速开始 public class Application { public static v ...

  9. 快速搭建react项目骨架(按需加载、redux、axios、项目级目录等等)

    一.前言 最近整理了一下项目骨架,顺便自定义了一个脚手架,方便日后使用.我会从头开始,步骤一步步写明白,如果还有不清楚的可以评论区留言.先大致介绍一下这个骨架,我们采用 create-react-ap ...

  10. 3.ifconfig

    Windows下查看IP地址用ipconfig Linux 下查看IP地址用ifconfig 还有 ip addr      而ipconfig 和ip addr的区别则是与net-tools工具和i ...