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

最近准备了解一下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
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值