查看: 105|回覆: 1

用c#操作Mongodb(附demo)

[複製鏈接]

2

主題

0

回帖

0

積分

热心网友

金币
0
閲讀權限
220
精華
0
威望
0
贡献
0
在線時間
0 小時
註冊時間
2008-12-17
發表於 2016-2-25 18:06:00 | 顯示全部樓層 |閲讀模式

因为需要,写了一个基于泛型的helper,这样要使用起来方便一点。

为了大家也不重复造轮子,所以发出来希望能帮到谁。

复杂的查询最好用linq,这也是mongodb官方建议的。

mongodb的C#配置

这部分很多文章都提到了,需要注意的是用的驱动与你的mongodb版本还有你.Net好像有点关系

我是mongodb-2.x,.NET4,driver我用的是1.x系列

2.x系列好像我这种配置用不起,大家可以试一试,貌似要.NET要4.5才行

驱动下载地址:

https://github.com/mongodb/mongo-csharp-driver

 

这里有个小坑,mongodb的数据库连接字符串和mysql是不一样的,很多文章没有提到完整的连接字符串,花半天在官网上看到了

mongodb://username:password@myserver:port/databaseName

 

Model的编写

其他没什么,但请注意ID、时间的类型,用的是mongdoDB自己的数据类型

这里用了一个虚函数,是为了方便helper里面用泛型获取id

 

以下是Model的源码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MongoDB.Driver;
using MongoDB.Bson;
namespace WindowsFormsApplication1.Model
{
    public abstract class MongoModel
    { 
        public ObjectId id { get; set; } 
        public BsonDateTime created_at { get; set; }
        public BsonDateTime updated_at { get; set; } 
    }

 public class AccountModel : MongoModel
    {
     //例子
public AccountModel() { } public string name { get; set; } } }

 

Helper的编写

因为mongodb的操作语句必须大量用到你的Model,因此考虑用泛型来做Helper

用Builder模式的原因无非是觉得好玩,你可以修改代码用构造函数直接初始化

我也没有用静态方法,你有需要可以自己修改

 

以下是helper的源码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
using MongoDB.Driver;
using MongoDB.Bson;
using MongoDB.Driver.Builders;

namespace FrameWork
{
    public class MongoHelper<T> where T : WindowsFormsApplication1.Model.MongoModel
    {
        public string conn;
        public string dbName;
        public string collectionName;

        private MongoCollection<T> collection;

        private MongoHelper()
        {

        }

        /// <summary>
        /// 设置你的collection
        /// </summary>
        public void SetCollection()
        {
            MongoClient client = new MongoClient(conn);
            var server = client.GetServer();
            var database = server.GetDatabase(dbName);
            collection = database.GetCollection<T>(collectionName);
        }

        /// <summary>
        /// 你用linq的时候会用到
        /// </summary>
        public void getCollection()
        {
            MongoClient client = new MongoClient(conn);
            var server = client.GetServer();
            var database = server.GetDatabase(dbName);
            collection = database.GetCollection<T>(collectionName);
        }

        /// <summary>
        /// 查找
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public T Find(IMongoQuery query)
        {
            return this.collection.FindOne(query);
        }

        /**
         * 条件查询用linq
         * http://mongodb.github.io/mongo-csharp-driver/1.11/linq/
         * */
        public List<T> FindAll()
        {
            return this.collection.FindAll().ToList();
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public long Update(T model)
        {
            BsonDocument doc = BsonExtensionMethods.ToBsonDocument(model);
            WriteConcernResult res = this.collection.Update(Query.EQ("_id", model.id), new UpdateDocument(doc));
            return res.DocumentsAffected;
        }

        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool Insert(T model)
        {
            WriteConcernResult res = this.collection.Insert(model);
            return res.Ok;
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool Delete(T model)
        {
            WriteConcernResult res = this.collection.Remove(Query.EQ("_id", model.id));
            return res.Ok;
        }

        /// <summary>
        /// 构造器
        /// </summary>
        /// <typeparam name="T"></typeparam>
        public class Builder<T> where T : WindowsFormsApplication1.Model.MongoModel
        {
            private MongoHelper<T> client;

            public Builder()
            {
                client = new MongoHelper<T>();
            }

            public void setConn(string conn)
            {
                client.conn = conn;
            }

            public void setDbName(string dbName)
            {
                client.dbName = dbName;
            }

            public void setCollectionName(string collectionName)
            {
                client.collectionName = collectionName;
            }

            public MongoHelper<T> build()
            {
                client.SetCollection();
                return client;
            }
        }
    }
}

 

Helper的使用

很简单,我写在demo的form代码里了,注释也写的很清楚什么流程

1.设计好你的model

2.初始化数据库配置

3.build一个helper

4.调用方法

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevComponents.DotNetBar;
using System.IO;
using FrameWork;

namespace WindowsFormsApplication1
{
    /**
     * 
     * MongoDB数据库增删改查DEMO
     * 任意拷贝、修改
     * 仅供学习
     * 曾维周 16/2/25
     * 
     * App独立开发群 533838427
     * 
     * */
    public partial class MainForm : DevComponents.DotNetBar.Metro.MetroForm
    {
        public Model.ConfModel conf = new Model.ConfModel();
        private bool isFirst = true;
        private string filePath;
        private List<Model.AccountModel> accounts = new List<Model.AccountModel>();
        private FrameWork.MongoHelper<Model.AccountModel> client;
        public MainForm()
        {
            InitializeComponent();
            this.Activated += new EventHandler(Form2_Activated);
        }

        void Form2_Activated(object sender, EventArgs e)
        {
            if (isFirst)
            {
                init();
                isFirst = false;
            }
        }

        void init()
        {
            /**
             * 
             * step-1
             * 配置你的mongodb链接
             * 请配置完
             * 
             * */
            conf.mongodb_dbAddr = "localhost";
        }

        private void buttonX2_Click(object sender, EventArgs e)
        {
            /**
             * 
             * step-2
             * 请操作前修改好你的model
             * 
             * step-3
             * 用builder初始化一个helper
             * 当然你也完全可以修改代码直接在构造函数里面初始化
             * 我是觉得好玩
             * 
             * */
            FrameWork.MongoHelper<Model.AccountModel>.Builder<Model.AccountModel> builder = new FrameWork.MongoHelper<Model.AccountModel>.Builder<Model.AccountModel>();
            builder.setCollectionName("你的collection名字");
            builder.setConn(conf.mongodb_conn);
            builder.setDbName(conf.mongodb_dbName);
            client = builder.build();
        }

        private void buttonX1_Click(object sender, EventArgs e)
        {
            //
            Model.AccountModel account = new Model.AccountModel();
            account.name = "love";
            client.Insert(account);

            //
            client.Delete(account);

            //
            account.name = "not love";
            client.Update(account);

            //
            Model.AccountModel res = client.Find(MongoDB.Driver.Builders.Query<Model.AccountModel>.EQ(xx => xx.id, account.id));

            //强烈建议用linq进行查询操作
            //http://mongodb.github.io/mongo-csharp-driver/1.11/linq/ 
            //var query = collection.AsQueryable<Model.AccountModel>().Where(e => e.FirstName == "John");

        }

    }
}

 

 

参考资料

http://mongodb.github.io/mongo-csharp-driver/1.11/linq/

http://blog.csdn.net/haukwong/article/details/7840158

http://www.cnblogs.com/viprx/archive/2012/09/07/2674637.html

demo下载

链接: http://pan.baidu.com/s/1qX3vfdE 密码: buh2

 

P.S.

希望能帮助到谁

自己建的一个群,希望广结英豪,尤其是像我一样脑子短路不用react硬拼anroid、ios原生想干点什么的朋友。

App独立开发群 533838427



来源:https://www.cnblogs.com/matoo/p/5217922.html
回覆

使用道具 舉報

0

主題

2091

回帖

1萬

積分

琼殿精英

金币
10576
閲讀權限
220
精華
0
威望
0
贡献
0
在線時間
0 小時
註冊時間
2011-10-11
發表於 6 天前 | 顯示全部樓層
哇,楼主太棒了!正好最近在研究MongoDB,这个demo太及时了!

先感谢楼主的无私分享!

看了一下楼主的代码,思路很清晰,用泛型封装确实比直接写MongoDB原生的API要方便很多,以后换Model也不需要改太多代码。

有个小问题想请教一下:
关于驱动版本的问题,1.x系列和2.x系列确实有很大区别。

我现在用的是MongoDB 3.x+.NET 4.5的环境,是不是直接用2.x系列的驱动就可以了?驱动版本和MongoDB服务器版本的对应关系有没有什么需要注意的?

另外,感觉楼主的Helper已经基本够用了,如果能加上批量操作(比如Batch Insert、Batch Update)就更完美了,有时候处理大量数据的时候还是很需要的。

还有连接字符串的格式确实是个坑,很多文章都没写清楚,楼主总结得很到位!

圆梦公社就需要这样热心的同学分享干货!支持楼主!

期待楼主更多的分享~ 鼓掌
回覆

使用道具 舉報

您需要登錄後才可以回帖 登錄 | 立即注册

本版積分規則

圆梦公社,专注于为全球华人提供纯粹技术交流的地方,请勿发布任何政治及违法的言论。如有相关侵权、举报、投诉及建议等,请发 E-mail:dzh188@hotmail.com

Powered by Discuz! X5.0 © 2001-2026 Discuz! Team.

在本版发帖返回顶部