歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux基礎 >> 關於Linux >> 在Linux系統下用C#開發MongoDB的步驟

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

日期:2017/2/25 11:51:41   编辑:關於Linux

  按照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();
}
}
}

  運行結果:

linux下C#開發mongoDB

  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”為系統自動生成的,相當於一個主鍵。

上一頁123下一頁查看全文 內容導航
  • 第1頁:查詢服務器中所有存在的數據庫
  • 第2頁:查詢數據,先通過上面的插入代碼
  • 第3頁:除基本增刪改查外 分布式文件系統規范
Copyright © Linux教程網 All Rights Reserved