Welcome 微信登录

首页 / 数据库 / MySQL / 使用MongoDB C#官方驱动操作MongoDB

想要在C#中使用MongoDB,首先得要有个MongoDB支持的C#版的驱动。C#版的驱动有很多种,如官方提供的,samus。 实现思路大都类似。这里我们先用官方提供的mongo-csharp-driver ,当前版本为1.7.0.4714下载地址:http://github.com/mongodb/mongo-csharp-driver/downloads编译之后得到两个dll MongoDB.Driver.dll:顾名思义,驱动程序 MongoDB.Bson.dll:序列化、Json相关 然后在我们的程序中引用这两个dll。 下面的部分简单演示了怎样使用C#对MongoDB进行增删改查操作。Program.csusing System;
using MongoDB.Driver;
using MongoDB.Bson;namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            //数据库连接字符串
            string conn = "mongodb://127.0.0.1:27017";
            //数据库名称
            string database = "RsdfDb";
            string collection = "Act_User";            MongoServer mongodb = MongoServer.Create(conn);//连接数据库
            MongoDatabase mongoDataBase = mongodb.GetDatabase(database);//选择数据库名
            MongoCollection mongoCollection = mongoDataBase.GetCollection(collection);//选择集合,相当于表
            mongodb.Connect();            //普通插入
            var o = new { UserID = 0, UserName = "admin", Password = "1" };
            mongoCollection.Insert(o);            //对象插入
            User user = new User { UserID = 1, UserName = "chenqp", Password = "1" };
            mongoCollection.Insert(user);            //BsonDocument 插入
            BsonDocument bd = new BsonDocument();
            bd.Add("UserID", 2);
            bd.Add("UserName", "yangh");
            bd.Add("Password", "1");
            mongoCollection.Insert(bd);            Console.ReadLine();        }
    } 
}User.csusing MongoDB.Bson;namespace ConsoleApplication1
{
    class User
    {
        //_id 属性必须要有,否则在更新数据时会报错:“Element "_id" does not match any field or property of class”。
        public ObjectId _id; //BsonType.ObjectId 这个对应了 MongoDB.Bson.ObjectId
        public int UserID { get; set; }
        public string UserName { get; set; }
        public string Password { get; set; }
    }
}shell 界面如下:更多MongoDB相关教程见以下内容:CentOS 编译安装 MongoDB与mongoDB的php扩展 http://www.linuxidc.com/Linux/2012-02/53833.htmCentOS 6 使用 yum 安装MongoDB及服务器端配置 http://www.linuxidc.com/Linux/2012-08/68196.htmUbuntu 13.04下安装MongoDB2.4.3 http://www.linuxidc.com/Linux/2013-05/84227.htmMongoDB入门必读(概念与实战并重) http://www.linuxidc.com/Linux/2013-07/87105.htmUbunu 14.04下MongoDB的安装指南 http://www.linuxidc.com/Linux/2014-08/105364.htm《MongoDB 权威指南》(MongoDB: The Definitive Guide)英文文字版[PDF] http://www.linuxidc.com/Linux/2012-07/66735.htmNagios监控MongoDB分片集群服务实战 http://www.linuxidc.com/Linux/2014-10/107826.htm基于CentOS 6.5操作系统搭建MongoDB服务 http://www.linuxidc.com/Linux/2014-11/108900.htmMongoDB 的详细介绍:请点这里
MongoDB 的下载地址:请点这里本文永久更新链接地址