使用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.cs

using 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.cs

using 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 6.5操作系统搭建MongoDB服务 http://www.linuxidc.com/Linux/2014-11/108900.htm

MongoDB 的详细介绍请点这里
MongoDB 的下载地址请点这里

猜你喜欢

转载自www.linuxidc.com/Linux/2015-12/126932.htm