原文链接 http://www.mongodb.org/display/DOCS/CSharp+Driver+Quickstart?showComments=true&showCommentArea=true#addcomment

介绍

本文的目的是让你对如何使用Mongodb的C#驱动有一个简单的了解,当你阅读完本文你就可以参考其他文章以了解更多信息。

下载C#驱动

你可以在这里下载需要的驱动。网站提供压缩包(zip)和安装包(msi)两种格式的驱动,下载完成后你可以将他解压或安装到你需要的目录。

添加C#驱动

在你的visual studio项目右击项目选择"Add Reference..."将如下两个dll添加到项目的引用中.

1. MongoDB.Bson.dll
2. MongoDB.Driver.dll

添加需要的命名空间

你的项目要使用MongoDB,至少需要下面两个命名空间

  1. using MongoDB.Bson;
  2. using MongoDB.Driver;
using MongoDB.Bson;
using MongoDB.Driver;

另外你也许需要下面这些命名空间

  1. using MongoDB.Driver.Builders;
  2. using MongoDB.Driver.GridFS;
  3. using MongoDB.Driver.Linq;
using MongoDB.Driver.Builders;
using MongoDB.Driver.GridFS;
using MongoDB.Driver.Linq;

获取服务器对象

获取服务器的连接对象非常简单

  1. var connectionString = "mongodb://localhost/?safe=true";
  2. var server = MongoServer.Create(connectionString);
var connectionString = "mongodb://localhost/?safe=true";
var server = MongoServer.Create(connectionString);

你应该在你的连接字符串中始终加上"safe=true"

或许你想用一个全局变量来保存你的服务器对象,其实当你使用相同的连接字符调用MongoServer.Create方法时返回的服务器对象是相同的对象引用,因此你无需采用全局变量来保存你的服务器对象在需要的时候调用MongoServer.Create方法即可。

获取数据库对象

获取数据库对象的方法如下:

  1. var database = server.GetDatabase("test"); // "test" is the name of the database
var database = server.GetDatabase("test"); // "test" is the name of the database

如果你需使用更多的数据库只需要多次调用server.GetDatabase()方法即可。

如何确定使用BsonDocument对象还是自定义类对象

你有两种方式来操作一个集合

1.使用BsonDocument对象。

2.使用自定义的类对象。

当你要处理的数据格式比较灵活难以用自定义的类来描述时你应该考虑采用BsonDocument来操作集合.

采用自定义的类对象可以让其他开发人员快速了解你的意图,自定义的类需要满足如下两个条件:

1.需要一个没有参数的构造函数。

2.定义公开的可读写的字段或属性来操作数据库中表相关的字段。

另外如果你要用自定义类操作根文档,你的类还必须包含一个ID属性。通常情况下id的类型为ObjectId。

获取集合对象

为了更好理解这个小节,我们采用一个名叫Entity的自定义类,你可以使用如下方式获取包含Entity文档的集合。

  1. var collection = database.GetCollection<Entity>("entities"); // "entities" is the name of the collection
var collection = database.GetCollection<Entity>("entities"); // "entities" is the name of the collection

插入一个文档

插入一个文档的方式非常简单

  1. var entity = new Entity { Name = "Tom" };
  2. collection.Insert(entity);
  3. var id = entity.Id; // Insert will set the Id if necessary (as it was in this example)
var entity = new Entity { Name = "Tom" };
collection.Insert(entity);
var id = entity.Id; // Insert will set the Id if necessary (as it was in this example)

查找文档

在这个列子中我将根据指定的id来获取相应的文档信息。

  1. var query = Query.EQ("_id", id);
  2. var entity = collection.FindOne(query);
var query = Query.EQ("_id", id);
var entity = collection.FindOne(query);

保存文档

你可以采用如下方式来保存一个已更改的文档

  1. entity.Name = "Dick";
  2. collection.Save(entity);
entity.Name = "Dick";
collection.Save(entity);

更新已存在的文档

另一种保存的方式就是更新。两种方法的不同点是Save()方法是将整个文档数据发回给服务器,而update()只是将更改的信息返回给服务器。

  1. var query = Query.EQ("_id", id);
  2. var update = Update.Set("Name", "Harry"); // update modifiers
  3. collection.Update(query, update);
var query = Query.EQ("_id", id);
var update = Update.Set("Name", "Harry"); // update modifiers
collection.Update(query, update);

删除已存在的文档

要删除集合中的一条文档信息写法如下:

  1. var query = Query.EQ("_id", id);
  2. collection.Remove(query);
var query = Query.EQ("_id", id);
collection.Remove(query);

你无需调用Connect() 或 Disconnect() 方法

C#驱动有个连接池以高效的管理服务器连接。你无需调用Connect() 或 Disconnect()方法,驱动会自动管理连接。调用Connect()方法没有什么坏处,但是不能调用Disconnect()方法因为调用该方法会关闭连接池中的所有连接。

完整的例子代码

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using MongoDB.Bson;
  6. using MongoDB.Driver;
  7. using MongoDB.Driver.Builders;
  8. namespace ConsoleApplication1
  9. {
  10. public class Entity
  11. {
  12. public ObjectId Id { get; set; }
  13. public string Name { get; set; }
  14. }
  15. class Program
  16. {
  17. static void Main(string[] args)
  18. {
  19. var connectionString = "mongodb://localhost/?safe=true";
  20. var server = MongoServer.Create(connectionString);
  21. var database = server.GetDatabase("test");
  22. var collection = database.GetCollection<Entity>("entities");
  23. var entity = new Entity { Name = "Tom" };
  24. collection.Insert(entity);
  25. var id = entity.Id;
  26. var query = Query.EQ("_id", id);
  27. entity = collection.FindOne(query);
  28. entity.Name = "Dick";
  29. collection.Save(entity);
  30. var update = Update.Set("Name", "Harry");
  31. collection.Update(query, update);
  32. collection.Remove(query);
  33. }
  34. }
  35. }

MongoDB--CSharp Driver Quickstart .的更多相关文章

  1. c#操作MangoDB 之MangoDB CSharp Driver驱动详解

    序言 MangoDB CSharp Driver是c#操作mongodb的官方驱动. 官方Api文档:http://api.mongodb.org/csharp/2.2/html/R_Project_ ...

  2. mongodb .net driver

    1.介绍 The official MongoDB .NET Driver provides asynchronous interaction with MongoDB. Powering the d ...

  3. MongoDB Java Driver操作指南

    MongoDB为Java提供了非常丰富的API操作,相比关系型数据库,这种NoSQL本身的数据也有点面向对象的意思,所以对于Java来说,Mongo的数据结构更加友好. MongoDB在今年做了一次重 ...

  4. MongoDB C Driver使用教程

    MongoDB C Driver使用教程 转载请注明出处http://www.cnblogs.com/oloroso/ 本指南提供简介 MongoDB C 驱动程序. 在 C API 的详细信息,请参 ...

  5. windows平台下安装、编译、使用mongodb C++ driver

    本博客将记录在Win8.1 ,VS2013环境下编译.配置mongodb C++ driver的流程. 1.下载预备 下载Boost:http://sourceforge.net/projects/b ...

  6. Ignoring Extra Elements in mongoDB C# Driver

    MongoDB删除字段后会报错: Element ... does not match any field or property of class Customer. 需要在实体类增加 [BsonI ...

  7. Mongodb Java Driver 参数配置解析

    要正确使用Mongodb Java Driver,MongoClientOptions参数配置对数据库访问的并发性能影响极大. connectionsPerHost:与目标数据库能够建立的最大conn ...

  8. mongodb c++ driver(2.53)windows编译

    编译环境: (1) 下载python2.7, 使用x86_32位,因为scons只有32位安装包可用: (2) 下载scons2.3.0,The current production release ...

  9. MongoDB C Driver and APIinstances linux MongoDB安装配置

    <一,linux平台MongoDB安装配置>在这我们使用的Centos6 yum部署的,你想搞编译,自个干!

随机推荐

  1. PHP迭代器的小坑

    使用PHP迭代器的时候,需要主要到很多迭代器是对内部迭代器的封装,当外部迭代器移动的时候,实际上也是在移动内部迭代器. 示例一:命令行 &"C:\wamp64\bin\php\php ...

  2. Java中private、protected、public和default的区别 (转)

    本文内容转载自: https://www.cnblogs.com/jingmengxintang/p/5898900.html public: 具有最大的访问权限,可以访问任何一个在classpath ...

  3. fullfile

    这个我总是忽略,见过也不少了,顺便写写,其实一些命令很方便的. 一个例子: root_dir = '../mcg/pre-trained'; addpath(root_dir); addpath(fu ...

  4. java模板导出PDF

    本次完善综合特点: 一对一,点对点的给对应的地方写值,比如模板里面放了个name标识,在程序里把“张三”赋给name,那么输出的pdf里面name的地方就变成了张三,准确方便快捷 支持中文,可以使用自 ...

  5. Codeforces 868F. Yet Another Minimization Problem【决策单调性优化DP】【分治】【莫队】

    LINK 题目大意 给你一个序列分成k段 每一段的代价是满足\((a_i=a_j)\)的无序数对\((i,j)\)的个数 求最小的代价 思路 首先有一个暴力dp的思路是\(dp_{i,k}=min(d ...

  6. 分析现有 WPF / Windows Forms 程序能否顺利迁移到 .NET Core 3.0(使用 .NET Core 3.0 Desktop API Analyzer )

    今年五月的 Build 大会上,微软说 .NET Core 3.0 将带来 WPF / Windows Forms 这些桌面应用的支持.当然,是通过 Windows 兼容包(Windows Compa ...

  7. vs2005新建项目中没有ASP.NET WEB应用程序的解决方法

    在vs2003的年代,我们可以在项目模板中选择创建"asp.net web应用程序",可是到vs2005中,就变成了创建网站,原有的创建"asp.net web应用程序& ...

  8. CentOS 6.5 下Nginx服务的安装与配置

    参考网站: http://www.cnblogs.com/zhuhongbao/archive/2013/06/04/3118061.html http://www.cnblogs.com/jilia ...

  9. CentOS6.5 下Haproxy服务的安装与配置

    参考网站: http://wenku.baidu.com/link?url=57AsCAL8TIv8NC3Vdnpd0hQ4fGNls8RFikjRWna3OaZb6qGHYTdV-4_wQPuzv8 ...

  10. vim之vundle

    git clone https://github.com/gmarik/vundle.git ~/.vim/bundle/vundle,下载到本地 gvim ~/.vimrc set nocompat ...