mongodb c# driver(驱动)介绍及CURD

mongodb c# driver(驱动)介绍

目前基于C#的mongodb驱动有两种,分别是官方驱动(下载地址)和samus驱动(下载地址)。
本次我们只演示官方驱动的使用方法。
官方驱动文档查看

第一步:引用驱动dll

引用驱动有两种方式:
1. 根据上面的下载地址下载对应的版本,然后引用到项目中。
2. 在项目的引用上右击->管理NuGet程序包(首先确保安装了nuget扩展包)->联机搜索官方驱动dll(搜索条件是 “Official MongoDB”)->安装成功后会引用3个dll(MongoDB.Driver和MongoDB.Bson,Newtonsoft.Json)。

第二步:构造MongodbHelper类

代码如下:

using MongoDB.Driver;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Server.DAL.DBHelper
{
    public sealed class MongodbHelper
    {
        static public readonly MongodbHelper Instance = new MongodbHelper();
        private MongoDatabase db;

        private MongodbHelper()
        {
            //http://www.studyofnet.com/news/337.html
            //mongodb://[username:[email protected]]host1[:port1][,host2[:port2],…[,hostN[:portN]]][/[database][?options]]
            string strconn = "mongodb://sa:[email protected]:27017";
            string dbName = "test";
            MongoDB.Driver.MongoClient mongoClient = new MongoClient(strconn);
            MongoServer server = mongoClient.GetServer();
            db = server.GetDatabase(dbName);
        }

        public MongoDatabase DB
        {
            get { return db; }
        }

        public MongoCollection this[string value]
        {
            get
            {
                return db.GetCollection(value);
            }
        }

     }
}

第三步:添加实体对象

在此建立的是一个复杂person对象,如下代码:

 public class Test:BaseEntity
{
}
public class PersonType : BaseEntity
{
    public string Code { get; set; }
    public string Display { get; set; }
}
public class Person : BaseEntity
{
    //如果对应多个分类,则格式为:,3,34,2
    public string PersonType { get; set; }
    public string Name { get; set; }
    public bool Sex { get; set; }
    public int Age { get; set; }

    public DateTime AddTime { get; set; }
    public List<Address> Addresses { get; set; }
    public List<string> Courses { get; set; }
}

public class Address
{
    public string Province { get; set; }
    public string City { get; set; }
}

BaseEntity说明

BaseEntity中放的是mongodb数据库中自动生成的_id(类型是ObjectId)

 public class BaseEntity
{
    /// <summary>
    /// 字段映射,告诉mongodb这个字段在数据库中对应_id
    /// </summary>
    [BsonId]
    //告诉mongodb这个字段在数据库中的类型是ObjectId
    [BsonRepresentation(BsonType.ObjectId)]
    public string _id { get; set; }
}

第四步:创建ApiController

创建ApiController基类BaseApiController

BaseApiController中会初始化一些变量,代码如下:

    public class BaseApiController : ApiController
    {
        public int skip, take;
        public MongoDatabase db;
        public MongoCollection col = null;//用于直接返回查询的json
        public BaseApiController(string collectionName)
        {
            skip = GetIntRequest("skip");
            take = GetIntRequest("take");
            if (skip == 0 && take == 0)
            {
                take = int.MaxValue;
            }

            db = Server.DAL.DBHelper.MongodbHelper.Instance.DB;
            col = db.GetCollection(collectionName);
        }
        public string GetStringRequest(string paramter)
        {
            return HttpContext.Current.Request.QueryString[paramter] ?? "";
        }
        public int GetIntRequest(string paramter)
        {
            string tmp = HttpContext.Current.Request.QueryString[paramter] ?? "";
            int tag = 0;
            int.TryParse(tmp, out tag);
            return tag;
        }
    }

创建TestController继承BaseApiController

我们就用TestController来演示CURD.
具体代码如下,不再做详细说明:

public class TestController : Filter.BaseApiController
{
    public TestController()
        : base("Person")
    {
    }

    public string Post([FromBody]object value)
    {
        var model = JsonConvert.DeserializeObject<Person>(value.ToString());
        model._id = ObjectId.GenerateNewId().ToString();
        try
        {
            col.Insert(model);
            return model._id;
        }
        catch (WebException ex)
        {
            throw ex;
        }
    }
    public object Get()
    {
        try
        {
            IEnumerable<Person> queryable = col.AsQueryable<Person>();
            Func<Person, bool> where = null;

            //有多少条件并多少条件

            //like
            //var name = GetStringRequest("Name");
            if (!string.IsNullOrEmpty(name))
            {
                where = c => c.Name.Contains(name);
                queryable = queryable.Where(where);
            }
            //单个条件等值查询
            var personType = GetStringRequest("personType");
            if (!string.IsNullOrEmpty(personType))
            {
                where = c => c.PersonType == personType;
                queryable = queryable.Where(where);
            }
            //嵌套数组查询
            var course = GetStringRequest("course");
            if (!string.IsNullOrEmpty(course))
            {
                where = c => c.Courses.Contains(course);
                queryable = queryable.Where(where);

            }
            //嵌套实体集合查询---查数量
            var address = GetStringRequest("address");
            if (!string.IsNullOrEmpty(address))
            {
                where = c => c.Addresses.Count > GetIntRequest("address");
                queryable = queryable.Where(where);

            }
            var personList = queryable.OrderByDescending(c => c._id).Skip(skip).Take(take).ToList();
            var count = queryable.Count();

            var data = new { count = count, dataList = personList };
            return data;
        }
        catch (WebException ex)
        {
            throw ex;
        }
    }

    public Person Get(string id)
    {
        try
        {
            var model = col.AsQueryable<Person>().FirstOrDefault(c => c._id == id);
            return model;
        }
        catch (WebException ex)
        {

            throw ex;
        }
    }

    //部分字段修改模式,只修改需要修改的字段。缺点是只能修改单个属性,对于嵌套数组和嵌套实体集合无法修改
    public int Put(string id, [FromBody]object value)
    {
        try
        {
            var query = new QueryDocument { { "_id", ObjectId.Parse(id) } };
            var dicData = JsonConvert.DeserializeObject<Dictionary<string, object>>(value.ToString());
            var update = new UpdateDocument { { "$set", new QueryDocument(dicData) } };
            col.Update(query, update);
            return 1;
        }
        catch (WebException ex)
        {
            throw ex;
        }

    }

    //完全修改模式,先查后改,支持任意类型的对象的修改。缺点是需要先查询一次
    public int Put([FromBody]object value)
    {
        try
        {
            var model = JsonConvert.DeserializeObject<Person>(value.ToString());
            col.Save(model);
            return 1;
        }
        catch (WebException ex)
        {

            throw ex;
        }

    }
    public void Delete(string id)
    {
        try
        {
            var query = new QueryDocument { { "_id", ObjectId.Parse(id) } };
            col.Remove(query);
        }
        catch (WebException ex)
        {

            throw ex;
        }
    }
}

第五步:CURD演示

在这里我们使用一个工具Fiddler2演示。

添加

*:first-child {
margin-top: 0 !important;
}

body>*:last-child {
margin-bottom: 0 !important;
}

/* BLOCKS
=============================================================================*/

p, blockquote, ul, ol, dl, table, pre {
margin: 15px 0;
}

/* HEADERS
=============================================================================*/

h1, h2, h3, h4, h5, h6 {
margin: 20px 0 10px;
padding: 0;
font-weight: bold;
-webkit-font-smoothing: antialiased;
}

h1 tt, h1 code, h2 tt, h2 code, h3 tt, h3 code, h4 tt, h4 code, h5 tt, h5 code, h6 tt, h6 code {
font-size: inherit;
}

h1 {
font-size: 28px;
color: #000;
}

h2 {
font-size: 24px;
border-bottom: 1px solid #ccc;
color: #000;
}

h3 {
font-size: 18px;
}

h4 {
font-size: 16px;
}

h5 {
font-size: 14px;
}

h6 {
color: #777;
font-size: 14px;
}

body>h2:first-child, body>h1:first-child, body>h1:first-child+h2, body>h3:first-child, body>h4:first-child, body>h5:first-child, body>h6:first-child {
margin-top: 0;
padding-top: 0;
}

a:first-child h1, a:first-child h2, a:first-child h3, a:first-child h4, a:first-child h5, a:first-child h6 {
margin-top: 0;
padding-top: 0;
}

h1+p, h2+p, h3+p, h4+p, h5+p, h6+p {
margin-top: 10px;
}

/* LINKS
=============================================================================*/

a {
color: #4183C4;
text-decoration: none;
}

a:hover {
text-decoration: underline;
}

/* LISTS
=============================================================================*/

ul, ol {
padding-left: 30px;
}

ul li > :first-child,
ol li > :first-child,
ul li ul:first-of-type,
ol li ol:first-of-type,
ul li ol:first-of-type,
ol li ul:first-of-type {
margin-top: 0px;
}

ul ul, ul ol, ol ol, ol ul {
margin-bottom: 0;
}

dl {
padding: 0;
}

dl dt {
font-size: 14px;
font-weight: bold;
font-style: italic;
padding: 0;
margin: 15px 0 5px;
}

dl dt:first-child {
padding: 0;
}

dl dt>:first-child {
margin-top: 0px;
}

dl dt>:last-child {
margin-bottom: 0px;
}

dl dd {
margin: 0 0 15px;
padding: 0 15px;
}

dl dd>:first-child {
margin-top: 0px;
}

dl dd>:last-child {
margin-bottom: 0px;
}

/* CODE
=============================================================================*/

pre, code, tt {
font-size: 12px;
font-family: Consolas, "Liberation Mono", Courier, monospace;
}

code, tt {
margin: 0 0px;
padding: 0px 0px;
white-space: nowrap;
border: 1px solid #eaeaea;
background-color: #f8f8f8;
border-radius: 3px;
}

pre>code {
margin: 0;
padding: 0;
white-space: pre;
border: none;
background: transparent;
}

pre {
background-color: #f8f8f8;
border: 1px solid #ccc;
font-size: 13px;
line-height: 19px;
overflow: auto;
padding: 6px 10px;
border-radius: 3px;
}

pre code, pre tt {
background-color: transparent;
border: none;
}

kbd {
-moz-border-bottom-colors: none;
-moz-border-left-colors: none;
-moz-border-right-colors: none;
-moz-border-top-colors: none;
background-color: #DDDDDD;
background-image: linear-gradient(#F1F1F1, #DDDDDD);
background-repeat: repeat-x;
border-color: #DDDDDD #CCCCCC #CCCCCC #DDDDDD;
border-image: none;
border-radius: 2px 2px 2px 2px;
border-style: solid;
border-width: 1px;
font-family: "Helvetica Neue",Helvetica,Arial,sans-serif;
line-height: 10px;
padding: 1px 4px;
}

/* QUOTES
=============================================================================*/

blockquote {
border-left: 4px solid #DDD;
padding: 0 15px;
color: #777;
}

blockquote>:first-child {
margin-top: 0px;
}

blockquote>:last-child {
margin-bottom: 0px;
}

/* HORIZONTAL RULES
=============================================================================*/

hr {
clear: both;
margin: 15px 0;
height: 0px;
overflow: hidden;
border: none;
background: transparent;
border-bottom: 4px solid #ddd;
padding: 0;
}

/* TABLES
=============================================================================*/

table th {
font-weight: bold;
}

table th, table td {
border: 1px solid #ccc;
padding: 6px 13px;
}

table tr {
border-top: 1px solid #ccc;
background-color: #fff;
}

table tr:nth-child(2n) {
background-color: #f8f8f8;
}

/* IMAGES
=============================================================================*/

img {
max-width: 100%
}
-->

时间: 2024-12-15 01:37:26

mongodb c# driver(驱动)介绍及CURD的相关文章

[原创]MongoDB C++ 驱动部分问题解决方案(MongoDB C++ Driver)

本文为我长时间开发以及修改MongoDB C++ Driver时的一些问题和解决方案.目前本文所介绍的相关引擎也已经发布闭源版本,请自行下载 库版本以及相关位置:http://code.google.com/p/mongodb-cpp-engine/ Q & A1.C++版本驱动我们需要另行封装么?A:并非一定要做此类行为,不过如果我们增加和使用一个连接池其稳定性将远远优于我们的想想. 2.C++版本的驱动除了官方版本外,还有什么版本么?A:目前未知,但我已经完成了一版线程安全的版本,下载地址:

MongoDB .Net Driver(C#驱动) - 内嵌数组/嵌入文档的操作(增加、删除、修改、查询(Linq 分页))

目录 一.前言 (一) 运行环境 二.前期准备工作 (一) 创建 MongoDBContext MongoDb操作上下文类 (二)创建测试类 (三) 创建测试代码 三.内嵌数组增加元素操作 (一) Update.Set()方法 替换内嵌数组(不推荐使用) (二)Update.Push()方法 直接将元素压入内嵌数组(推荐) (三) Update.PushEach()方法 将多个元素压入内嵌数组(推荐) 四.内嵌数组删除元素操作 (一) Update.Set()方法 替换内嵌数组(不推荐使用) (

windows下mongodb基础玩法系列二CURD操作(创建、更新、读取和删除)

windows下mongodb基础玩法系列 windows下mongodb基础玩法系列一介绍与安装 windows下mongodb基础玩法系列二CURD操作(创建.更新.读取和删除) 简单说几句 在mongodb中3元素:db(数据库).collection(集合).document(文档) 其中collection类似于数据库中的表,document类似于行,这样一来我们就将内容对比起来记忆学习了. 数据格式 MongoDB documents是BSON格式(一种类json的一种二进制形式的存

收录mongodb C# driver 说明

C# driver Releases notes C# driver 指南(博客园友翻译) Mongodb Connection String mongodb的write concern 各版本驱动解决的问题(JIRA) 收录mongodb C# driver 说明,布布扣,bubuko.com

windows下mongodb基础玩法系列二CURD附加一

windows下mongodb基础玩法系列 windows下mongodb基础玩法系列一介绍与安装 windows下mongodb基础玩法系列二CURD操作(创建.更新.读取和删除) windows下mongodb基础玩法系列二CURD附加一 说在前面的话 在系列二中CURD只是简单的走了一下代码操作的流程,其中全是简单基础操作的内容, 在我仔细看完接下来的内容后决定再丰富一下前面的操作,并实战一个简单的demo出来,demo具体搭配语言暂时决定在PHP与nodejs之间. 增加内容至文档没说完

【转载】8天学通MongoDB——第八天 驱动实践

作为系列的最后一篇,得要说说C#驱动对mongodb的操作,目前驱动有两种:官方驱动和samus驱动,不过我个人还是喜欢后者, 因为提供了丰富的linq操作,相当方便. 官方驱动:https://github.com/mongodb/mongo-csharp-driver/downloads.下载后,还提供了一个酷似msdn的帮助文档. samus驱动:https://github.com/samus/mongodb-csharp/downloads. 下面就具体看看samus驱动,https:

MongoDB的Java驱动使用整理 (转)

MongoDB Java Driver 简单操作 一.Java驱动一致性 MongoDB的Java驱动是线程安全的,对于一般的应用,只要一个Mongo实例即可,Mongo有个内置的连接池(池大小默认为10个).  对于有大量写和读的环境中,为了确保在一个Session中使用同一个DB时,我们可以用以下方式保证一致性:  DB mdb = mongo.getDB('dbname');  mdb.requestStart(); // // 业务代码 // mdb.requestDone(); DB和

MongoDB资料--Java驱动, Hadoop驱动, Spark使用

Part 1 W3CSchool的MongoDB Java: http://www.w3cschool.cc/mongodb/mongodb-java.html MongoDB的Java驱动使用整理: http://blog.163.com/wm_at163/blog/static/132173490201110254257510/ MongoDB的java版本驱动: http://www.aichengxu.com/view/13226 Mongo-Java-Driver下载: http://

MongoDB官方C#驱动中查询条件Query用法

http://www.cnblogs.com/viprx/archive/2012/09/06/2673693.html MongoDB条件查询的基本语法. Query.All("name", "a", "b");//通过多个元素来匹配数组  Query.And(Query.EQ("name", "a"), Query.EQ("title", "t"));//同时满足