六狼论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

新浪微博账号登陆

只需一步,快速开始

搜索
查看: 105|回复: 0

C#连接MongoDB数据库应用实战

[复制链接]

升级  61%

113

主题

113

主题

113

主题

举人

Rank: 3Rank: 3

积分
383
 楼主| 发表于 2013-1-12 13:26:43 | 显示全部楼层 |阅读模式
1、下载驱动
  C#驱动的下载地址为:
  远程下载:http://cloud.github.com/downloads/mongodb/mongo-csharp-driver/CSharpDriver-1.1.0.4184.zip
 
 本地下载  CSharpDriver-1.1.0.4184.zip
 
  将其解压到D:\mongodb\drivers\目录下,其中有2个重要的dll文件
    MongoDB.Bson.dll --序列化、Json相关
    MongoDB.Driver.dll --驱动
  2、添加引用
  新建一个C#的项目,添加引用,将上面两个dll文件引入到项目里面:


  3、代码解析
  下面以一个插入的操作为例,来一步一步解释代码:
<div style="padding-right: 5.4pt; padding-left: 5.4pt; background: #e6e6e6; padding-bottom: 4px; width: 97%; padding-top: 4px;">using System;
using System.Collections.Generic;
using System.Linq;
using System.
Text;
//添加命名空间
using MongoDB.Bson;
using MongoDB.Driver;
namespace ConsoleApplication3
{
    class Program
    {
        static void Main(string
[] args)
        {
            
//MongoDB服务器连接串
            string connectionString
= "mongodb://192.168.1.103";
            MongoServer server
= MongoServer.Create(connectionString);
            
//连接到 mongodb_c_demo 数据库
            MongoDatabase db
= server.GetDatabase("mongodb_c_demo");
            
//获取集合 fruit
            MongoCollection collection
= db.GetCollection("fruit");
            
//创建对象 fruit_1
            BsonDocument fruit_1
= new BsonDocument
            {
              { "webste", "http://www.my400800.cn" },
              { "name", "400电话" }
            };
            
//创建对象 fruit_2
            BsonDocument fruit_2
= new BsonDocument
            {
              { "
webste", "http://www.hrxc.net" },
              { "
name", "华仁信诚" }
            };
            
//将对象 fruit_1 放到集合 fruit 中
            collection.
Insert(fruit_1);
            
//将对象 fruit_2 放到集合 fruit 中
            collection.
Insert(fruit_2);
            
//以上代码完成的就是向fruit表中插入2条数据,用mysql的语法解释即
            
//insert into mongodb_c_demo.fruit (name, color)
            
//values ('webste', 'name'), ('http://www.hrxc.net', '华仁信诚');
        }
    }
}
您需要登录后才可以回帖 登录 | 立即注册 新浪微博账号登陆

本版积分规则

快速回复 返回顶部 返回列表