在Linux系統下用C#開發MongoDB的步驟

來源:互聯網
上載者:User

首先按   介紹的方法安裝好monodevelop和mono開發環境

按照mongoDB官方的例子安裝好mongoDB在linux上:http://www.mongodb.org/display/DOCS/Quickstart+Unix,注意根據CPU是32位還是64位下載不同的版本

開啟一個終端啟動mongoDB的資料庫服務 root@Ubuntu:/usr/local/mongoDB/bin# ./mongod

在接下來的過程中,建立一個資料庫gywdb來做測試。奇怪的事情是mongoDB沒有直接建立資料庫的命令,找了半天沒找到,後來只有通過間接的方式來建立。如下命令所示。

開啟一個新的終端:預設串連到的資料庫是test

root@ubuntu:/usr/local/mongoDB/bin# ./mongo
MongoDB shell version: 2.0.4
connecting to: test

建立自己的資料庫gywdb

 use gywdb
switched to db gywdb
> db.createCollection("student",{});
{ "ok" : 1 }
這樣資料庫gywdb建立成功了,而且建立了一個student的表。

下面是通過C#來操作mongoDB的一些代碼

運行命令 show dbs 檢查下資料庫是否建立成功。
gywdb    0.203125GB
local    (empty)
test    0.203125GB
可以看到gywdb建立好了。

下面是通過C#驅動代碼來實現mongoDB的各種操作。

1、查詢服務器中所有存在的資料庫

using System;using System.Collections;using System.Collections.Generic;using MongoDB.Bson;using MongoDB.Driver;namespace mongoDBClient{    class MainClass    {        public static void Main (string[] args)        {            //mongoDb服務執行個體連接字串            string con="mongodb://localhost:27017";            //得到一個於mongoDB伺服器串連的執行個體            MongoServer server=MongoServer.Create(con);                            IEnumerable<string> names=server.GetDatabaseNames();            foreach(string name in names)                Console.WriteLine(name);            Console.ReadLine();        }    }}

運行結果:

2、插入文檔資料到資料表student中去

using System;using System.Collections;using System.Collections.Generic;using MongoDB.Bson;using MongoDB.Driver;namespace mongoDBClient{    class MainClass    {        public static void Main (string[] args)        {            //mongoDb服務執行個體連接字串            string con="mongodb://localhost:27017";            //得到一個於mongoDB伺服器串連的執行個體            MongoServer server=MongoServer.Create(con);                        //獲得一個與具體資料庫連接對象,資料庫名為gywdb            MongoDatabase mydb=server.GetDatabase("gywdb");                //獲得資料庫中的表對象,即student表            MongoCollection mydbTable=mydb.GetCollection("student");            //準備一條資料,即申明一個文檔對象            BsonDocument doc=new BsonDocument            {                {"name","令狐少俠"},                {"classname","華山派"},                {"age",100}            };             //將文檔插入,持久化到硬碟上            mydbTable.Insert(doc);                             Console.ReadLine();        }    }}

通過命令查看結果: > db.student.find();
{ "_id" : ObjectId("4f852ce41d41c80d9b090110"), "name" : "令狐少俠", "classname" : "華山派", "age" : 100 }

可以看到表中有剛才通過代碼加入的一條資料了,其中欄位“_id”為系統自動產生的,相當於一個主鍵。

  • 1
  • 2
  • 3
  • 下一頁

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.