Mongodb学习一,开始使用C# Driver操作Mongodb

来源:互联网 发布:北京 抑郁症 知乎 编辑:程序博客网 时间:2024/06/05 02:29

最近准备了解一下Mongodb,顺便在这里做一个总结。本章讲解一下简单的安装和操作。


首先,安装Mongodb:

D:\MongoDB

1、从官方下载好安装包;

2、新建目录“D:\MongoDB”,解压安装包,将bin目录中的exe文件拷贝到新建目录之下;

3、在D:\MongoDB目录下创建“Data”文件夹,打开CMD窗口,切换到D:\MongoDB目录,输入“mongod --dbpath D:\MongoDB\Data ”。

结果如图:


可以在浏览器中输入:http://localhost:27017/,会看到:

It looks like you are trying to access MongoDB over HTTP on the native driver port.

如此,MongoDB数据库服务以及启动。


然后,下载驱动:https://github.com/mongodb/mongo-csharp-driver/releases


最后,我们可以开始使用C#操作Mongodb了:


1、将以下DLL引入到工程:

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


2、直接拷贝官网的例子:

using System;using System.Collections.Generic;using System.Linq;using System.Text;using MongoDB.Bson;using MongoDB.Driver;using MongoDB.Driver.Builders;namespace ConsoleApplication1{    public class Entity    {        public ObjectId Id { get; set; }        public string Name { get; set; }    }    class Program    {        static void Main(string[] args)        {    //链接字符串            var connectionString = "mongodb://localhost";    //定义Mongo服务             var client = new MongoClient(connectionString);            var server = client.GetServer();    //获取databaseName对应的数据库,不存在则自动创建             var database = server.GetDatabase("test");    //获取 "entities" 对应的集合,不存在则自动创建             var collection = database.GetCollection<Entity>("entities");            var entity = new Entity { Name = "Tom" };    //将对象插入集合             collection.Insert(entity);            var id = entity.Id;<span style="white-space:pre"></span>    // 定义查询对象(id为entity.id,这里为null)            var query = Query<Entity>.EQ(e => e.Id, id);    // 在集合中查找符合query条件的Entity对象            entity = collection.FindOne(query);            entity.Name = "Dick";    // 保存对象,这里将发送到服务器端            collection.Save(entity);    // 更新对象,这里只更新模型,不会发送到服务器端            var update = Update<Entity>.Set(e => e.Name, "Harry");            collection.Update(query, update);    // 从集合中移除符合条件的对象            collection.Remove(query);        }    }}

单步调试就可以看到结果了,当然也以在里面加入一些输出语句观察结果。

执行完成后打开数据文件夹,发现里面多了 test.0和test.ns两个文件。


官方文档中有这样一段话值得注意:

You Do NOT Need to Call Connect or Disconnect

The C# driver has a connection pool to use connections to the server efficiently. There is no need to callConnect or Disconnect; just let the driver take care of the connections (calling Connect is harmless, but calling Disconnect is bad because it closes all the connections in the connection pool).

意思不需要调用Connect(),或者Disconnect(),尤其后者,它将关闭连接池中的所有连接。

0 0