1. 程式人生 > >用c#操作Mongodb(附demo)

用c#操作Mongodb(附demo)

b數 lba var ini event .net dal query lin

用c#操作Mongodb(附demo)

因為需要,寫了一個基於泛型的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

用c#操作Mongodb(附demo)