.Net Core MongoDB 简单操作。
一:MongoDB 简单操作类。这里引用了MongoDB.Driver。
using MongoDB.Bson;
using MongoDB.Driver;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks; namespace WebEFCodeFirst.MongoDBPro
{
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("db");
collection = db.GetCollection<BsonDocument>("londb");
}
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 projection = Builders<BsonDocument>.Projection.Exclude("_id");
var document = collection.Find(new BsonDocument()).Project(projection).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",);
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;
}
}
}
二:控制器类
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using MongoDB.Bson;
using WebEFCodeFirst.Models;
using WebEFCodeFirst.MongoDBPro; namespace WebEFCodeFirst.Controllers
{
public class MongoDBController : Controller
{
private MongoDBOperation<BsonDocument> mongo = null;
public MongoDBController()
{
mongo = MongoDBOperation<BsonDocument>.GetMongoDBInstance();
}
public ActionResult Index()
{
var document = new BsonDocument
{
{ "name", "MongoDB" },
{ "type", "Nosql" },
{ "count", },
};
List<MongodbModel> mdlist = new List<MongodbModel>(); //MongodbModel model = new MongodbModel();
if (mongo != null)
{
//long result = mongo.DeleteData();//删除 //mongo.InsertOneData(document);//插入一行数据
List<BsonDocument> document1 = mongo.FindAnsyncData();
//List<BsonDocument> list = mongo.FindData();
//mongo.UpdateOneData(list[0]["_id"].ToString(), document); //BsonDocument 支持索引查询。
ViewData["name"] = document1[]["name"].ToString();
ViewData["type"] = document1[]["type"].ToString();
ViewBag.Name = document1[]["name"].ToString();
ViewBag.Type = document1[]["type"].ToString(); for (int i = ; i < document1.Count; i++)
{
MongodbModel model = new MongodbModel(); model.name = document1[i]["name"].ToString();
model.type1 = document1[i]["type"].ToString();
model.count = document1[i]["count"].ToString(); mdlist.Add(model);
}
}
//return PartialView("/*_MongoDBPartial*/", mdlist);
return View(mdlist);
} public IActionResult querymongodb(string dbname)//[FromBody] object paras)// string[] arr)
{
//if (arr.Length <= 0)
//{
// return null;
//}
dbname = Request.Query["dbname"].ToString();// Get请求 //dbname = Request.Form["dbname"].ToString();//POST请求
if (string.IsNullOrEmpty(dbname.ToString()))
{
return null;
} var document = new BsonDocument
{
{ "name", dbname.ToString() },
{ "type", "DB"},
};
List<MongodbModel> mdlist = new List<MongodbModel>(); if (mongo != null)
{
List<BsonDocument> document1 = mongo.FindFilterlData(document);
for (int i = ; i < document1.Count; i++)
{
MongodbModel model = new MongodbModel(); model.name = document1[i]["name"].ToString();
model.type1 = document1[i]["type"].ToString();
model.count = document1[i]["count"].ToString(); mdlist.Add(model);
}
}
return PartialView("_MongoDBPartial", mdlist);
//return View(mdlist);
} [HttpPost]
public IActionResult querymon(string dbname)
{
dbname = Request.Form["dbname"].ToString(); var document = new BsonDocument
{
{ "name", dbname },
{ "type", dbname},
};
List<MongodbModel> mdlist = new List<MongodbModel>(); if (mongo != null)
{
List<BsonDocument> document1 = mongo.FindFilterlData(document);
for (int i = ; i < document1.Count; i++)
{
MongodbModel model = new MongodbModel(); model.name = document1[i]["name"].ToString();
model.type1 = document1[i]["type"].ToString();
model.count = document1[i]["count"].ToString(); mdlist.Add(model);
}
}
return PartialView("_MongoDBPartial", mdlist);
//return View(mdlist);
}
[HttpPost]
public IActionResult OnPostSearchquerymon(string dbname2)
{
if (string.IsNullOrEmpty(dbname2))
{
return null;
}
var document = new BsonDocument
{
{ "name", dbname2 },
{ "type", "DB"},
};
List<MongodbModel> mdlist = new List<MongodbModel>(); if (mongo != null)
{
List<BsonDocument> document1 = mongo.FindFilterlData(document);
for (int i = ; i < document1.Count; i++)
{
MongodbModel model = new MongodbModel(); model.name = document1[i]["name"].ToString();
model.type1 = document1[i]["type"].ToString();
model.count = document1[i]["count"].ToString(); mdlist.Add(model);
}
}
return View(mdlist);
} public IActionResult Create()
{
return View();
} [HttpPost]
public async Task<IActionResult> Create(string dbname)
{
dbname = Request.Form["dbname"].ToString();
string dbtye = Request.Form["dbtye"].ToString();
string dbcount = Request.Form["dbcount"].ToString(); if (string.IsNullOrEmpty(dbname))
{
return RedirectToAction(nameof(Index));
} var document = new BsonDocument
{
{ "name", dbname },
{ "type", dbtye},
{ "count",dbcount},
}; if (mongo != null)
{
await mongo.InsertAsyncOneData(document);
}
return RedirectToAction(nameof(Index));
}
}
}
三:视图
@model IEnumerable<WebEFCodeFirst.Models.MongodbModel>
<style>
th, td {
padding: 3px;
}
</style>
<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script src="~/lib/jquery/dist/jquery.js"></script> <p>
<h3> <a asp-action="Create">注册</a> </h3>
</p> <div class="row">
<p></p>
<div class="col-md-12">
<form action="post">
<div class="row-fluid">
名称:<input type="text" id="dbname" name="dbname2" value=@ViewBag.Name />
类型:<input type="text" id="dbtype" value=@ViewBag.Name />
<input type="button" asp-controller="MongoDB" asp-action="querymon" id="mongodbtest" value="查询" />
<input type="button" asp-page-handler="Searchquerymon" id="mongodbte" value="查询handler" />
<input type="submit" id="sbquery" value="查询sub" />
</div> <div class="table table-striped" id="datamain">
@Html.Partial("/Views/Shared/_MongoDBPartial.cshtml", Model)@*页面load时候。*@
</div>
</form>
<p></p>
<ul id="messages" style="list-style-type:none;"></ul>
</div>
</div>
<script>
//新增数据。2018.3.23 14:38
// Ajax Get方法。
$(document).ready(function () {
$("#mongodbte").click(function () {
var txtNo1 = $("#dbname").val();
var txtName1 = $("#dbtype").val(); var model = [];
model.push($("#dbname").val(), $("#dbtype").val());
$.ajax({
url: "/MongoDB/querymongodb",//规定发送请求的 URL。默认是当前页面
data: { dbname: model.toString() }, //json时,一定要是key-value.规定要发送到服务器的数据
type: "GET",//规定请求的类型(GET 或 POST)。
contentType: "json",//"application/json;charset=utf-8",//数据类型必须有,指定发给服务端的数据格式。
async: true,//异步处理 success: function (datas) {
$("#datamain").html(datas);
//console.log(datas);
},
error: function (datas) {
alert("刷新失败!");
} });//ajax()方法要放在事件中调用。
});
}); //Ajax Post方法 2018.3.24 14:12
$(document).ready(function () {
$("#mongodbtest").click(function () {
var txtNo1 = $("#dbname").val();
var txtName1 = $("#dbtype").val(); var model = [];
model.push($("#dbname").val(), $("#dbtype").val()); $.ajax({
url: "/MongoDB/querymon",//规定发送请求的 URL。默认是当前页面
data: { dbname: txtNo1, dbtye: txtName1 }, //json时,一定要是key-value.规定要发送到服务器的数据
type: "POST",//规定请求的类型(GET 或 POST)。
contentType: "application/x-www-form-urlencoded",//Post用这种类型,//数据类型必须有,指定发给服务端的数据格式。
async: true,//异步处理 success: function (datas) {
$("#datamain").html(datas);
//console.log(datas); .net core 自带log4
},
error: function (datas) {
alert("刷新失败!");
} });//ajax()方法要放在事件中调用。
});
});
</script>
四:效果图

附加:
默认情况下控制器和视图关系:

.Net Core MongoDB 简单操作。的更多相关文章
- MongoDB简单操作
Hadoop核心技术厂商Cloudera将在2014/06推出hadoop Ecosystem与MongoDB的整合产品,届时MongoDB与ipmala及hbase,hive一起用; 开源linux ...
- MongoDB 简单操作
MongoDB操作 之 原生ORM,根本不存在SQL语句,数据之间不存在联系 查看数据库(查看磁盘中的数据库) > show databases; 使用数据库 > use local 创建 ...
- Node js MongoDB简单操作
//win7环境下node要先安装MongoDB的相关组件(非安装MongoDB数据库),在cmd命令行进入node项目目录后执行以下语句 //npm install mongodb //创建连接 v ...
- MongoDB简单操作(java版)
新建maven项目,添加依赖: <dependency> <groupId>org.mongodb</groupId> <artifactId>mong ...
- C# Asp.net中简单操作MongoDB数据库(一)
需要引用MongoDB.Driver.dll.MongoDB.Driver.core.dll.MongoDB.Bson.dll三个dll. 1.数据库连接: public class MongoDb ...
- C# 对MongoDB 进行增删改查的简单操作
C# 对MongoDB 进行增删改查的简单操作 下面演示下C#操作MongoDB驱动的简单的增删改查代码 运用到的MongoDB支持的C#驱动,当前版本为1.6.0 1,连接数据库 /// & ...
- C# Asp.net中简单操作MongoDB数据库(二)
C# Asp.net中简单操作MongoDB数据库(一) , mongodb数据库连接可以回顾上面的篇幅. 1.model类: public class BaseEntity { /// < ...
- Golang 对MongoDB的操作简单封装
使用MongoDB的Go驱动库 mgo,对MongoDB的操作做一下简单封装 初始化 操作没有用户权限的MongoDB var globalS *mgo.Session func init() { s ...
- MongoDB数据库简单操作
之前学过的有mysql数据库,现在我们学习一种非关系型数据库 一.简介 MongoDB是一款强大.灵活.且易于扩展的通用型数据库 MongoDB 是由C++语言编写的,是一个基于分布式文件存储的开源数 ...
随机推荐
- Office 365 Connectors 的使用与自定义开发
前言 我相信很多人都看过<三国演义>,里面有很多引人入胜的故事和栩栩如生的人物,对我而言,曹操手下的一员猛将典韦实在让我印象深刻.例如,书中有一段描写典韦的作战经历: 时西面又急,韦进当之 ...
- 论文笔记(3):STC: A Simple to Complex Framework for Weakly-supervised Semantic Segmentation
论文题目是STC,即Simple to Complex的一个框架,使用弱标签(image label)来解决密集估计(语义分割)问题. 2014年末以来,半监督的语义分割层出不穷,究其原因还是因为pi ...
- springboot如何测试打包部署
有很多网友会时不时的问我,spring boot项目如何测试,如何部署,在生产中有什么好的部署方案吗?这篇文章就来介绍一下spring boot 如何开发.调试.打包到最后的投产上线. 开发阶段 单元 ...
- RedHat 7.3 更新yum源
title: RedHat 7.3 更新yum源 time: 2018.3.15 查看所有yum包 [root@bogon ~]# rpm -qa | grep yum yum-rhn-plugin- ...
- C++学习-4
1.一个类重写了operator(),可以f()-相当于匿名对象-f()()相当于调用operator()函数 把对象名当成函数名来使用--伪函数 2.通过成员函数创建多线程 a) 可以用成员函 ...
- spring boot rest例子
简介: 本文将帮助您使用 Spring Boot 创建简单的 REST 服务. 你将学习 什么是 REST 服务? 如何使用 Spring Initializr 引导创建 Rest 服务应用程序? 如 ...
- Unity 读取资源(图片)
方法一: 采用Resource.Load方法读取,读取在Unity中Assets下Resources目录下的资源名(不采用后缀). //图片放在Asset/Resources/ Texture2D t ...
- 想在网上保持匿名?教你用Linux如何实现!
想在网上保持匿名?教你用Linux如何实现! 信息时代给我们的生活带来极大便利和好处的同时也带来了很大的风险.一方面,人们只要点击几下按钮,就能基本上访问已知存在的全部信息和知识:另一方面,要是这种权 ...
- Elasticsearch就这么简单
一.前言 最近有点想弄一个站内搜索的功能,之前学过了Lucene,后来又听过Solr这个名词.接着在了解全文搜索的时候就发现了Elasticsearch这个,他也是以Lucene为基础的. 我去搜了几 ...
- elasticsearch------java操作之QueryBuilders构建搜索Query
版权声明:本文为非原创文章,出处:http://blog.csdn.net/xiaohulunb/article/details/37877435. elasticsearch 分布式搜索系列专栏:h ...