csharp: MongoDB

安装配置:

Install MongoDB on Windows(安装配置官方参考) http://docs.mongodb.org/manual/tutorial/install-mongodb-on-windows/

1.Run MongoDB

C:\Program Files\MongoDB\Server\3.0\bin\mongod.exe --dbpath d:\data\db

#配置数据库
mongod.exe --dbpath d:\data\db
#配置日志文件
mongod.exe --logpath D:\data\logs\mongodb.log --install

#测试用户登录

mongo -u geovindu -p

2.C# 连接字符串

<!--<add key="connectionString" value="Server=localhost:27017"/>-->
<!--<add key="connectionString" value="mongodb://localhost:27017"/>-->
<!--<add key="connectionString" value="Server=127.0.0.1:27017"/>-->
<add key="connectionString" value="mongodb://127.0.0.1:27017"/>


以上四项都可以

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using MongoDB.Bson;
using MongoDB.Driver;

namespace MongoDB2.Model
{
    /// <summary>
    /// Wrapper class to communicate with ‘MyCompany‘ database.
    /// </summary>
    class MyCompany
    {

        /// <summary>
        ///
        /// </summary>
        public MyCompany()
        {

        }

        /// <summary>
        /// Connection string to the Mongo database server
        /// </summary>
        public static string ConnectionString
        {
            get
            {
                return ConfigurationManager.AppSettings["connectionString"];
            }
        }

        /// <summary>
        /// Creates sample data for two collections(or tables) i.e, Departments, Employees.
        /// </summary>
        public static void CreateData()
        {
            CreateDepartments();
            CreateEmployees();
        }

        #region Departments 

        /// <summary>
        /// Retrieve departments from MyCompany database.
        /// </summary>
        /// <returns></returns>
        public static List<Department> GetDepartments()
        {
            List<Department> lst = new List<Department>();

            MongoServer server = MongoServer.Create(ConnectionString);
            MongoCredentials credentials = new MongoCredentials("geovindu", "geovindu");
            MongoDatabase myCompany = server.GetDatabase("geovinDB");//,credentials//MyCompany
            MongoCollection<Department> departments = myCompany.GetCollection<Department>("Departments");
            foreach (Department department in departments.FindAll())
            {
                lst.Add(department);
            }

            return lst;
        }

        /// <summary>
        /// Inserts sample departments data in MyCompany database
        /// </summary>
        private static void CreateDepartments()
        {
            string headOfDepartmentId;

            //insert department ‘Development‘
            headOfDepartmentId = "4f180083ef31ba0da8000010";
            CreateDepartment("Development", headOfDepartmentId);

            //insert department ‘Accounts‘
            headOfDepartmentId = "4f180083ef31ba0da8000011";
            CreateDepartment("Accounts", headOfDepartmentId);

            //insert department ‘Human Resource‘
            headOfDepartmentId = "4f180083ef31ba0da8000012";
            CreateDepartment("Human Resource", headOfDepartmentId);
        }

        /// <summary>
        /// Insert the department
        /// </summary>
        /// <param name="departmentName"></param>
        /// <param name="headOfDepartmentId"></param>
        private static void CreateDepartment(string departmentName, string headOfDepartmentId)
        {
            MongoServer server = MongoServer.Create(ConnectionString);
            MongoCredentials credentials = new MongoCredentials("geovindu", "geovindu");
            MongoDatabase myCompany = server.GetDatabase("geovinDB");//, credentials //MyCompany

            MongoCollection<BsonDocument> departments = myCompany.GetCollection<BsonDocument>("Departments");
            BsonDocument deptartment = new BsonDocument {
                        { "DepartmentName", departmentName },
                        { "HeadOfDepartmentId", headOfDepartmentId }
                        };

            departments.Insert(deptartment);
        }

        /// <summary>
        /// Delete all data in departments collection in MyCompany database
        /// </summary>
        public static void DeleteDepartments()
        {
            MongoServer server = MongoServer.Create(ConnectionString);

            MongoCredentials credentials = new MongoCredentials("geovindu", "geovindu");
            MongoDatabase myCompany = server.GetDatabase("geovinDB");//, credentials//MyCompany

            MongoCollection<Department> departments = myCompany.GetCollection<Department>("Departments");
            departments.Drop();
        }
        #endregion

        #region Employees 

        /// <summary>
        /// Retrieve employees from MyCompany database.
        /// </summary>
        /// <returns></returns>
        public static List<Employee> GetEmployees()
        {
            List<Employee> lst = new List<Employee>();

            MongoServer server = MongoServer.Create(ConnectionString);
            MongoCredentials credentials = new MongoCredentials("geovindu", "geovindu");
            MongoDatabase myCompany = server.GetDatabase("geovinDB");//, credentials//无验证密码登录

            MongoCollection<Employee> employees = myCompany.GetCollection<Employee>("Employees");
            foreach (Employee employee in employees.FindAll())
            {
                lst.Add(employee);
            }

            return lst;
        }

        /// <summary>
        /// Inserts sample employees data in MyCompany database
        /// </summary>
        private static void CreateEmployees()
        {
            // add 5 sample Employees
            for (int i = 1; i <= 5; i++)
            {
                string departmentId = "4f180083ef31ba0da8000010";
                CreateEmployee("FirstName" + i, "LastName" + i, "Address" + i, "City" + i, departmentId);
            }
        }

        /// <summary>
        /// Insert the employee
        /// </summary>
        /// <param name="departmentName"></param>
        /// <param name="headOfDepartmentId"></param>
        private static void CreateEmployee(string firstName, string lastName, string address, string city, string departmentId)
        {
            MongoServer server = MongoServer.Create(ConnectionString);
            MongoCredentials credentials = new MongoCredentials("geovindu", "geovindu");
            MongoDatabase myCompany = server.GetDatabase("geovinDB");//, credentials//MyCompany

            MongoCollection<BsonDocument> employees = myCompany.GetCollection<BsonDocument>("Employees");
            BsonDocument employee = new BsonDocument {
                        { "FirstName", firstName },
                        { "LastName", lastName },
                        { "Address", address },
                        { "City", city },
                        { "DepartmentId", departmentId }
                        };

            employees.Insert(employee);
        }

        /// <summary>
        /// Delete all data in employees collection in MyCompany database
        /// </summary>
        public static void DeleteEmployees()
        {
            MongoServer server = MongoServer.Create(ConnectionString);
            MongoCredentials credentials = new MongoCredentials("geovindu", "geovindu");
            MongoDatabase myCompany = server.GetDatabase("geovinDB");//, credentials//MyCompany

            MongoCollection<Employee> employees = myCompany.GetCollection<Employee>("Employees");
            employees.Drop();
        }
        #endregion
    }

    #region Department
    /// <summary>
    /// Department represents a single item(record) stored in Departments collection.
    /// </summary>
    class Department
    {
        public ObjectId _id { get; set; }
        public string DepartmentName { get; set; }
        public ObjectId HeadOfDepartmentId { get; set; }
    }
    #endregion

    #region Employee
    /// <summary>
    /// Department represents a single item(record) stored in Employees collection.
    /// </summary>
    class Employee
    {
        public ObjectId _id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Address { get; set; }
        public string City { get; set; }
        public ObjectId DepartmentId { get; set; }
    }
    #endregion
}

  

时间: 2024-11-05 12:35:33

csharp: MongoDB的相关文章

mongodb 查询的用法

想要在C#中使用MongoDB,首先得要有个MongoDB支持的C#版的驱动.C#版的驱动貌似有很多种,如官方提供的samus. 实现思路大都类似.这里我们用官方提供的mongo-csharp-driver : 下载地址:http://github.com/mongodb/mongo-csharp-driver/downloads 解压之后得到两个dll: MongoDB.Driver.dll:顾名思义,驱动程序 MongoDB.Bson.dll:序列化.Json相关 然后在我们的程序中引用这两

看门外汉如何实现:C#操作 MongoDB基本CURD的事务控制

第一部分 基本设计 目前最新版本的C#驱动MongoDB-CSharpDriver-2.2.3,比之前的版本更新比较大,在网上很难找到这个版本的相关C#操作资料,以下都是个人自发研究.测试的,如有雷同,不胜荣幸:如觉不妥,留言喷射:如有错误,还请赐教:如获帮助,示意欣赏.新版中有很多异步操作,本人对此没作研究,怕会产生数据安全问题,所以全部用的是同步方法. 1. 模型设计,使用GUID类型做为Id属性,在初始化时给一个随机值,基类代码,不作解释 using System;using System

Using MongoDB with Web API and ASP.NET Core

MongoDB is a NoSQL document-oriented database that allows you to define JSON based documents which are schema independent. The schema can be mapped with Tables in a Relational Database. A schema in MongoDB is called as collection, and a record in thi

看门外汉如何实现:C#操作 MongoDB基本CURD的事务控制之 第二部分

第二部分 尝试解决BulkWrite(List<WriteModel<T>>)问题 在上次发表的文章中,得到了一些很好的反馈,真切体会到写博文的好处,有高人指出两大问题,具体可以看看上篇中的评论,下面依然是发表一些个人见解,只做研究,并不保证解决实际问题. 这两大问题终究来说,是发生在BulkWrite(List<WriteModel<T>>)上,针对@ 从来不用 的问题,我试着找出影响的行数据还比对写入操作的数量,如果一致,则提交,如果不一致则回滚. 1.

基于C#的MongoDB数据库开发应用(1)--MongoDB数据库的基础知识和使用

在花了不少时间研究学习了MongoDB数据库的相关知识,以及利用C#对MongoDB数据库的封装.测试应用后,决定花一些时间来总结一下最近的研究心得,把这个数据库的应用单独作为一个系列来介绍,希望从各个方面来总结并记录一下这个新型.看似神秘的数据库使用过程.本文是这个系列的开篇,主要介绍一些MongoDB数据库的基础知识.安装过程.基础使用等方面. MongoDB是一款由C++编写的高性能.开源.无模式的常用非关系型数据库产品,是非关系数据库当中功能最丰富.最像关系数据库的数据库.它扩展了关系型

MongoDB学习笔记~官方驱动嵌套数组对象的更新

回到目录 对于数组对象mongodb本身是支持的,不过对于数组的更新,mongodb的Csharp驱动目前只支持一级,即你的对象里包含数组,而数组又包括数组,这表示两层,这在更新子数组时,Csharp驱动是不支持的,今天要说的就是如何让它支持子数组的更新,下面是我给出的数据结构 在Mongodb的Csharp驱动里,一般的更新方法如下 update = new UpdateDocument {{ "$set", new BsonDocument("OrderList.$.Us

开发基于C#.NET的mongodb桌面版的应用程序(1)

1.之前没有使用过C#开发过相应的桌面应用程序,现在既然要从零到有进行开发,自然要掌握好C#桌面开发相关的原理与技术,mongodb具有生产意义的数据管理操作,以及站在多种类型的用户开发的具有实际生产意义的数据库管理软件产品. 2.选择github作为源代码托管环境,由于我选择了在windows环境下进行开发,所以需要安装一个windows版本的Github桌面应用程序(当前时间的有效链接:https://windows.github.com/),我进入页面的时候下载了这么一个东东: 接下来,点

asp.net 使用 MongoDB 初体验

首先:驱动 如果asp.net 想使用MongoDB,.net没有自带的链接类.得用第三方或官方的链接类. 当然有很多种驱动,我就不一一介绍了. 今天我就介绍一个我比较常用的驱动-----MongoDB. 接下来,我们还要去下载MongoDB的C#驱动,它可以让我们在C#中使用MongoDB .下载地址:https://github.com/samus/mongodb-csharp 我们在C#访问MongoDB所需的驱动就是项目MongoDB了.编译这个项目就能得到了,文件名:MongoDB.d

封装一个MongoDB的 asp.net 链接类

using System; using System.Collections.Generic; using System.Linq; using MongoDB; /// <summary> /// 对Mongo和MongoDatabase的包装类 /// </summary> public class MyMongoDb : IDisposable { private Mongo _mongo; private IMongoDatabase _db; private static