• .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>

    四:效果图

     附加:

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

  • 相关阅读:
    section_4.python操作mysqlsql注入导入导出数据库
    section_3.单表多表查询
    section_2.约束索引存储引擎
    Section_1.Mysql基础
    day7.线程-线程队列进程池和线程池回调函数协程
    Mysql小技巧总汇
    常用对照表的参考_chapter-one(Content-Type)
    ORACLE 数据库配置
    Shiro入门(用户权限控制)
    Quartz定时任务调度机制解析(CronTirgger、SimpleTrigger )
  • 原文地址:https://www.cnblogs.com/longdb/p/8722230.html
Copyright © 2020-2023  润新知