.Net Core MongoDB 简单操作。

longdb 2018-04-05 原文

.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",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;
        }
    }
}

二:控制器类

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", 2 },
            };
            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[0]["name"].ToString();
                ViewData["type"] = document1[1]["type"].ToString();
                ViewBag.Name = document1[0]["name"].ToString();
                ViewBag.Type = document1[1]["type"].ToString();

                for (int i = 0; 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 = 0; 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 = 0; 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 = 0; 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));
        }
    }
}

View Code

三:视图

@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>

四:效果图

 

发表于 2018-04-05 13:36 longdb 阅读() 评论() 编辑 收藏

 

版权声明:本文为longdb原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/longdb/p/8722230.html

.Net Core MongoDB 简单操作。的更多相关文章

  1. .NET平台系列22:.NET Core/.NET5/.NET6 对比 .NET Framework

    系列目录     【已更新最新开发文章,点击查看详细】   在我的博客《.NET平台系列2 .NET Fram […]...

  2. .Net调用钉钉接口,实现发送企业消息功能

    .Net调用钉钉接口,实现发送企业消息功能 我在钉钉官网上看了下,关于调用钉钉接口,发送企业消息通知,他给的核 […]...

  3. ASP.NET Core 依赖注入最佳实践与技巧

    ASP.NET Core 依赖注入最佳实践与技巧 原文地址:https://medium.com/voloso […]...

  4. Dapr Pub/Sub 集成 RabbitMQ 、Golang、Java、DotNet Core

    前置条件:《Dapr运用》《Dapr 运用之 Java gRPC 调用篇》《Dapr 运用之集成 Asp.Ne […]...

  5. 【C#】根据开始时间和结束时间筛选存在的信息

    背景 业务需求中,需要根绝开始时间和结束时间筛选一段时间内的任务存在个数。 示例图片 根据开始时间 9:00到 […]...

  6. ASP VNext 开源服务容错处理库Polly使用文档

    在进入SOA之后,我们的代码从本地方法调用变成了跨机器的通信。任何一个新技术的引入都会为我们解决特定的问题,都 […]...

  7. .Net Core使用分布式缓存Redis:基础

    一、前言   Redis的介绍网上很多不再赘述。本次环境为net core 2.2,使用的StackExcha […]...

  8. 面试官:你刚说你喜欢研究新技术,那么请说说你对 Blazor 的了解

    阅读本文大概需要 1.5 分钟。 最近在几个微信 .NET 交流群里大家讨论比较频繁的话题就是这几天自己的面试 […]...

随机推荐

  1. 轻松部署calico

    ### 一、资源 官方文档 “` https://docs.projectcalico.org/v […]...

  2. 【SwiftUI】学习笔记1-创建第一个iOS应用

    本系列将会开发大量实际的项目。系列为本人学习笔记,资料:《SwiftUI自学成长笔记》-刘铭资源源代码下载资源:可以在gitee上下载,搜索刘铭即可。第一章:创建项目也可以在菜单栏的File中选择Project...来创建项目然后选...

  3. 彻底搞懂感受野的含义与计算

    目录 什么是感受野 约定 感受野大小 感受野中心 小结 参考 博客:博客园 | CSDN | blog 什么是 […]...

  4. Eclipse/MyEclipse怎么设置个性化代码注释模板

    打开Eclipse/MyEclipse工具,打开或创建一个Java工程,点击菜单Window->Pref […]...

  5. 小程序跳转遇到的坑

    新手跳坑。你写的路径路由是正确的,但是发现点击了,一点反应也没有,很可能是下下面几种原因: 1:你要跳转的是t […]...

  6. 对本周知识的回顾以及心得

     例如:1/方法的作用是分而治之和重用 ,2/形参的本质是变量,起作用是接收实参的值,调用方法时,形参和实参要 […]...

  7. Oracle知识点详解

    一:概述     一、简介        1. 概念:Oracle 数据库是 ORACLE 公司提供的以分布式 […]...

  8. LayIM.AspNetCore Middleware 开发日记(七)Asp.Net.Core.SignalR闪亮登场

    前言   前几篇介绍了整个中间件的构成,路由,基本配置等等.基本上没有涉及到通讯部分。不过已经实现了融云的通讯 […]...

展开目录

目录导航