用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
P.S.
希望能帮助到谁
自己建的一个群,希望广结英豪,尤其是像我一样脑子短路不用react硬拼anroid、ios原生想干点什么的朋友。
App独立开发群 533838427
用c#操作Mongodb(附demo)的更多相关文章
- Koa 操作 Mongodb 数据库
node-mongodb-native的介绍 使用基于官方的 node-mongodb-native 驱动,封装一个更小.更快.更灵活的 DB 模块, 让我们用 nodejs 操作 Mongodb 数 ...
- Asp.net MVC集成Google Calendar API(附Demo源码)
Asp.net MVC集成Google Calendar API(附Demo源码) Google Calendar是非常方便的日程管理应用,很多人都非常熟悉.Google的应用在国内不稳定,但是在国外 ...
- java操作mongodb & springboot整合mongodb
简单的研究原生API操作MongoDB以及封装的工具类操作,最后也会研究整合spring之后作为dao层的完整的操作. 1.原生的API操作 pom.xml <!-- https://mvnre ...
- Python操作MongoDB和Redis
1. python对mongo的常见CURD的操作 1.1 mongo简介 mongodb是一个nosql数据库,无结构化.和去中心化. 那为什么要用mongo来存呢? 1. 首先.数据关系复杂,没有 ...
- C#开发微信公众平台-就这么简单(附Demo)转载
C#开发微信公众平台-就这么简单(附Demo) 来源:https://www.cnblogs.com/xishuai/p/3625859.html#!comments 写在前面 阅读目录: 服务号和 ...
- Android 浮动窗口进阶——画中画,浮动视频(附Demo)
今天继续上一篇Android顶层窗口.浮动窗口的进阶应用.上一篇主要讲解了WindowManager服务和如何使用WindowManager编写一个顶层窗口.今天主要是讲讲如何在顶层窗口里面播放视频, ...
- C# 操作 MongoDB
今项目使用Mongodb,C#操作MongoDB使用MongoDB.Driver.dll库(Nuget),写了个小Demo,如下: using System; using System.Collect ...
- PHP操作MongoDB数据库的示例
http://www.jquerycn.cn/a_8137 本节内容:PHP操作MongoDB数据库的简单示例. Mongodb的常用操作参看手册,php官方的http://us2.php.net/m ...
- FMDB的使用方法(附Demo)
http://www.jianshu.com/p/54e74ce87404 最近在项目中需要在多个页面对同样的数据进行相关操作,于是便用到了FMDB数据库操作,以下便是FMDB的一些简单的使用方法.附 ...
随机推荐
- Access 2003 中自定义菜单栏
在Access中如何用自定义的菜单代替Access自带的菜单,现在做一个简单的介绍: 1.打开您做的Access数据库: 2.单击工具栏,选择“自定义…”: 3.在“自定义”窗口,单击“工具栏”选项卡 ...
- JSP连接数据库
1.将c3p0-0.9.5.2.jar/mchange-commons-java-0.2.11.jar/ojdbc6.jar三个包放在WEB-INF的lib文件夹下,将web.xml文件放到WEB-I ...
- 初次体验VS2015正式版,安装详细过程。
本文版权归mephisto和博客园共有,欢迎转载,但须保留此段声明,并给出原文链接,谢谢合作. 文章是哥(mephisto)写的,SourceLink 阅读目录 介绍 安装 其他 本文版权归mephi ...
- google-analytics.com
最近有朋友问,为什么我的网站打开时在执行google analytics有较长的停顿时间.要如果解决?这个问题其实很早就有,最好的解决办法是将网站所有页面的传统追踪代码统一替换为最新的异步追踪代码.不 ...
- 002.ICMP--拼接ICMP包,实现简单Ping程序(原始套接字)
一.大致流程: 将ICMP头和时间数据设置好后,通过创建好的原始套接字socket发出去.目的主机计算效验和后会将数据原样返回,用当前时间和返回的数据结算时间差,计算出rtt. 二.数据结构: ICM ...
- [转]ASP.NET MVC 3 Razor + jqGrid 示例
本文转自:http://www.cnblogs.com/think8848/archive/2011/07/15/2107828.html 前些天写了一篇有关jqGrid的文章,因为是公司项目的原因一 ...
- Binary Tree: Write a function to return count of nodes in binary tree which has only one child.
June 8, 2015 我最喜欢的一道算法题目, 二行代码. 编程序需要很强的逻辑思维, 严密,我还没有很好训练自己.想一想, 二行代码, 五分钟就可以搞定; 最近这几天网上大家热议的 Homebr ...
- Java 三大特性——封装、继承、多态
一.封装 封装,实际就是把属于同一类事物的共性(包括属性与方法)归到一个类中,以方便使用. 概念:在面向对象程式设计方法中,封装(英语:Encapsulation)是指,一种将抽象性函式接口的实作细节 ...
- HDU 2117 取(2堆)石子游戏【wzf博弈】
题意:威佐夫博弈原型,除了输出先手能不能胜,还要输出先手的第一手选择. 思路:预处理出1000000以内的所有奇异局势.对于每个自然数,其必然是某一个奇异局势的a或者b.故对于一个非奇异局势,必定有一 ...
- IT菜鸟的3(for循环+分支语句)
第三天学的东西感觉已经不是很容易能想通了,感觉头懵懵的,难道这就是是文科生的障碍吗,我不相信,坚持!相信自己一定会做好! 1:for循环!(1)循环四要素:初始条件,循环条件,循环体,状态改变for( ...