因为需要,写了一个基于泛型的helper,这样要使用起来方便一点。
为了大家也不重复造轮子,所以发出来希望能帮到谁。
复杂的查询最好用linq,这也是mongodb官方建议的。
这部分很多文章都提到了,需要注意的是用的驱动与你的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
其他没什么,但请注意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; }
}
}
因为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;
}
}
}
}
很简单,我写在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
链接: http://pan.baidu.com/s/1qX3vfdE 密码: buh2
原文:http://www.cnblogs.com/zxtceq/p/7692209.html