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
}

  

 

posted @ 2015-09-09 17:04  ®Geovin Du Dream Park™  阅读(592)  评论(0编辑  收藏  举报