1. 程式人生 > >MongoDB安裝配置及CRUD操作

MongoDB安裝配置及CRUD操作

1.下載
https://www.mongodb.com/download-center
本文下載版本:Windows Server 2008 R2 64-bit

2.安裝
預設安裝路徑:C:\Program Files\MongoDB\Server\3.2\bin

3.將MongoDB伺服器作為Windows服務執行:
在E盤建立兩個目錄:
E:\MongoDB\log\
E:\MongoDB\data
控制檯輸入命令,建立服務:
<span style="font-size:18px;">mongod.exe --bind_ip 127.0.0.1 --logpath "E:\MongoDB\log\MongoDB.log" --logappend --dbpath "E:\MongoDB\data" --port 27017 --serviceName "MongoDBService" --serviceDisplayName "MongoDBDisplayNameOne" --install</span>

附:關閉服務和刪除程序
 > d:\mongodb\bin>NET stop MongoDB   (關閉服務)
 > d:\mongodb\bin>mongod --dbpath "d:\mongodb\data\db" --logpath "d:\mongodb\data\log\MongoDB.log" --remove --serviceName "MongoDB"   
   (刪除,注意不是--install了)

4.MongoDB的控制檯操作:
進入mongoDB控制檯:在mongodb的bin安裝目錄,輸入mongo命令:
> mongo
MongoDB shell version: 3.0.6
connecting to: test
……

5.管理工具
http://rockmongo.com/downloads 下載RockMongo-on-Windows 
解壓後啟動:rockstart.bat  
預設使用者名稱密碼:admin
(http://127.0.0.1:7788/rockmongo/ )

6.C# .net操作

Nuget下載MongoDB包:


MongoDB操作類:

<span style="font-size:18px;">    class MongoDBHandle
    {
        private static string mongoDbServer = ConfigurationManager.AppSettings["mongoConnection"];
        private static string mongoDbName = ConfigurationManager.AppSettings["mongoDb"];
    
        protected static IMongoClient _client;
        protected static IMongoDatabase _database;
        private IMongoClient client;
        private IMongoDatabase database;
        //private IMongoCollection<T> collection;
        public MongoDBHandle()
        {

            if (_client == null)
                _client = new MongoClient(mongoDbServer);
            if (_database == null)
                _database = _client.GetDatabase(mongoDbName);
        }
        public static void getConnection()
        {
          
        }

        public async  void insertDB()
        {
            TestUser users = new TestUser();
            users.Name = "xumingxiang";
            users.Sex = "man";
            //獲得Users集合,如果資料庫中沒有,先新建一個

            var collection = _database.GetCollection<TestUser>("restaurants");
            await collection.InsertOneAsync(users);
        }
        public async void queryDB()
        {
            var collection = _database.GetCollection<BsonDocument>("restaurants");
            //var filter = new BsonDocument();
            var filter = Builders<BsonDocument>.Filter.Eq("Name", "xumingxiang");//查詢條件
            var count = 0;
            using (var cursor = await collection.FindAsync(filter))
            {
                while (await cursor.MoveNextAsync())
                {
                    var batch = cursor.Current;
                    foreach (var document in batch)
                    {
                        // process document
                        count++; //查詢結果操作
                    }
                }
            }
        }
        public async void updateDB()
        {
            var collection = _database.GetCollection<BsonDocument>("restaurants");
            var filter = Builders<BsonDocument>.Filter.Eq("Name", "xumingxiang");//查詢條件
            var update = Builders<BsonDocument>.Update.Set("Sex", "woman");//更新欄位
            var result = await collection.UpdateOneAsync(filter, update);

        }

        public async void deleteDB()
        {
            var collection = _database.GetCollection<BsonDocument>("restaurants");
            var filter = Builders<BsonDocument>.Filter.Eq("Name", "xumingxiang");//查詢條件
            var result = await collection.DeleteManyAsync(filter);//刪除

        }

       
    }</span>

AppConfig配置:
<span style="font-size:18px;">  <appSettings>

    <add key="mongoConnection" value="mongodb://localhost:27017" />
    <add key="mongoDb" value="TestUserNew" />
  </appSettings></span>
TestUser類:
<span style="font-size:18px;">    public class TestUser
    {

            public ObjectId _id;//BsonType.ObjectId 這個對應了 MongoDB.Bson.ObjectId 
            public string Name { get; set; }
            public string Sex { set; get; }
        
    }</span>
呼叫:
<span style="font-size:18px;">        private void button1_Click(object sender, EventArgs e)
        {
            MongoDBHandle mongoDBHandle = new MongoDBHandle();
            mongoDBHandle.insertDB();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            MongoDBHandle mongoDBHandle = new MongoDBHandle();
            mongoDBHandle.queryDB();
        }

        private void button3_Click(object sender, EventArgs e)
        {
            MongoDBHandle mongoDBHandle = new MongoDBHandle();
            mongoDBHandle.updateDB();
        }

        private void button4_Click(object sender, EventArgs e)
        {
            MongoDBHandle mongoDBHandle = new MongoDBHandle();
            mongoDBHandle.deleteDB();
        }</span>

用線上工具檢視操作結果: