用C#操作Mongodb(c#mongodb驅動)
MongoDB的C#驅動基於.Net 3.5的 必要用.net 3.5以上的框架
1.對資料庫的操作主要還是增刪改查
2.瞭解c#操作mapreduce的語法
我們先佈置驅動環境,再通過例項來了解一下相關操作語法。
方法一:驅動工程直接下載:
https://github.com/mongodb/mongo-csharp-driver/downloads
下載驅動。驅動有兩個檔案
- MongoDB.Bson.dll
- MongoDB.Driver.dll
可以直接下載這兩個驅動,或者遵守下載原始碼進行編譯生成。下載的原始碼可以看些test例子
方法二:驅動原始碼下載後編譯得到驅動工程
地址:
https://github.com/mongodb/mongo-csharp-driver
下載的是原始碼,進行編譯後就可以得到MongoDB.Bson.dll,MongoDB.Driver.dll這兩個驅動。
驅動說明:
http://docs.mongodb.org/ecosystem/tutorial/use-csharp-driver/
驅動說明中文翻譯:
http://www.bwxxkj.com/a/jishuzhongxin/shujukukaifa/2013/0109/160953.html
驅動API說明:
http://api.mongodb.org/csharp/current/
下面通過例項操作來熟悉一下:
引入驅動:
在新建的c#工程中新增這兩個dll檔案並引用它們,並且應用如下定名空間
至少要引用如下定名空間
using MongoDB.Bson;
using MongoDB.Driver;
用得比較多的名稱空間
using MongoDB.Driver.Builders;
using MongoDB.Driver.GridFS;
using MongoDB.Driver.Linq;
可能用到的名稱空間
把這兩檔案複製進工程中using MongoDB.Bson.IO; using MongoDB.Bson.Serialization; using MongoDB.Bson.Serialization.Attributes; using MongoDB.Bson.Serialization.Conventions; using MongoDB.Bson.Serialization.IdGenerators; using MongoDB.Bson.Serialization.Options; using MongoDB.Bson.Serialization.Serializers; using MongoDB.Driver.Wrappers;
引用它們
新增名稱空間
好 可以用了 下面開始進行操作
對mongodb的資料進行操作有兩種方法:
1.先構造好類的結構,用這個結構操作資料。
2.直接操作資料。
插入資料:
方法一:
增加一個Student類,構建student的構造。
類的程式碼如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace mymongotest
{
class Student_Insert
{
public string 姓名{get;set;}
public string 學號{get;set;}
public Information[] 個人資訊{get;set;}
}
class Information
{
public string Name { get; set; }
public string Value { get; set; }
}
}
引用名稱空間:
using MongoDB.Bson.Serialization;
using MongoDB.Driver.Builders;
插入按鈕的程式碼:
private void button1_Click(object sender, EventArgs e)
{
MongoClient client;
MongoServer server;
MongoDatabase database;
var conStr = "mongodb://192.168.0.188";
client = new MongoClient(conStr);
server = client.GetServer();
database = server.GetDatabase("test");
var coll = database.GetCollection("student");
var sInsert = @"{""姓名"":""劉備"",""學號"":""001"",
""個人資訊"":[
{""Name"":""性別"",""Value"":""男""},
{""Name"":""班級"",""Value"":""1班""},
{""Name"":""專業"",""Value"":""物理""}
]
}";
var bd = BsonSerializer.Deserialize<Student_Insert>(sInsert);
coll.Insert(bd);
MessageBox.Show("入庫結束");
}
執行,點選插入按鈕
用MongoVue檢視結果
插入成功
方法二:
不構造類結構,直接建立文件插入資料。可以根據你的需要構造成不同的格式。
這裡 我們構造跟方法一一樣的格式:
MongoClient client;
MongoServer server;
MongoDatabase database;
var conStr = "mongodb://192.168.0.188";
client = new MongoClient(conStr);
server = client.GetServer();
database = server.GetDatabase("test");
var coll = database.GetCollection("student");
BsonDocument bd = new BsonDocument();
bd.Add(new BsonElement("姓名", "趙雲"));
bd.Add(new BsonElement("學號", "002"));
//個人資訊格式構造一: bd.Add(new BsonDocument{{"個人資訊",new BsonDocument{{"性別","男"},{"班級","1班"},{"專業","數學"}}}});
/* 個人資訊格式構造二:
BsonArray ba = new BsonArray();
BsonDocument information = new BsonDocument();
information.Add(new BsonElement("性別", "男"));
information.Add(new BsonElement("班級", "002"));
information.Add(new BsonElement("專業", "數學"));
ba.Add(information);
bd.Add(new BsonDocument("個人資訊", ba));
*/
//個人資訊格式3
//BsonArray ba = new BsonArray();
//ba.Add(new BsonDocument("性別", "男"));
//ba.Add(new BsonDocument("班級", "002"));
//ba.Add(new BsonDocument("專業", "數學"));
//bd.Add(new BsonDocument("個人資訊", ba));
//個人資訊格式4
BsonArray ba = new BsonArray();
ba.Add(new BsonDocument { { "Name", "性別" }, { "Value", "男" } });
ba.Add(new BsonDocument { { "Name", "班級" }, { "Value", "2班" } });
ba.Add(new BsonDocument { { "Name", "專業" }, { "Value", "物理" } });
bd.Add(new BsonDocument("個人資訊", ba));
coll.Insert(bd);
MessageBox.Show("入庫結束");
結果如下:
插入成功
查詢資料:
在已建的類Student程式碼裡新增類結構:Student_Query
新增後類Student.cs的程式碼為:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace mymongotest
{
class Student_Insert
{
public string 姓名{get;set;}
public string 學號{get;set;}
public Information[] 個人資訊{get;set;}
}
class Information
{
public string Name { get; set; }
public string Value { get; set; }
}
class Student_Query
{
public Object _id { get; set; }
public string 姓名 { get; set; }
public string 學號 { get; set; }
public Information[] 個人資訊 { get; set; }
}
}
情景一:通過索引值取資料----通常用於取上一條,下一條資料。(用到類結構)
在窗體下宣告集合coll和浮標cucor:
MongoCollection<Student_Query> coll;
MongoCursor<Student_Query> cursor;
宣告位置如圖:
查詢按鈕的程式碼:
private void button3_Click(object sender, EventArgs e)
{
MongoClient client;
MongoServer server;
MongoDatabase database;
var conStr = "mongodb://192.168.0.188";
client = new MongoClient(conStr);
server = client.GetServer();
database = server.GetDatabase("test");
coll = database.GetCollection< Student_Query>("student");
cursor = coll.FindAll();
var ex = cursor.ElementAt< Student_Query>(0);//取第一個資料
string sResult = "";
sResult = string.Format("{0}{1}{2}{3}{4}", ex.姓名, ex.學號, ex.個人資訊[0].Value, ex.個人資訊[1].Value, ex.個人資訊[2].Value);
MessageBox.Show(sResult);
}
結果:
情景二:用條件查詢
情景二方法一:(用類結構)
查詢按鈕程式碼如下:
MongoClient client;
MongoServer server;
MongoDatabase database;
var conStr = "mongodb://192.168.0.188";
client = new MongoClient(conStr);
server = client.GetServer();
database = server.GetDatabase("test");
coll = database.GetCollection<Student_Query>("student");
// var bs = coll.FindOne(Query.EQ("_id", new ObjectId("512c14c211f9d518809d8d0c")));
var bs = coll.FindOne(Query.EQ("姓名", "趙雲"));
string sResult = "";
sResult = string.Format("{0}{1}{2}{3}{4}", bs.姓名, bs.學號, bs.個人資訊[0].Value, bs.個人資訊[1].Value, bs.個人資訊[2].Value);
MessageBox.Show(sResult);
結果:
情景二方法二:(不用類結構)
查詢按鈕程式碼如下:
MongoClient client;
MongoServer server;
MongoDatabase database;
var conStr = "mongodb://192.168.0.188";
client = new MongoClient(conStr);
server = client.GetServer();
database = server.GetDatabase("test");
var coll = database.GetCollection("student");
// var bs = coll.FindOne(Query.EQ("_id", new ObjectId("512c14c211f9d518809d8d0c")));
var bs = coll.FindOne(Query.EQ("姓名", "趙雲"));
string sResult = "";
sResult = string.Format("{0}{1}{2}{3}{4}", bs.AsBsonDocument["姓名"].ToString(), bs.AsBsonDocument["學號"].ToString(), bs.AsBsonDocument["個人資訊"].AsBsonArray[0].AsBsonDocument["Value"].ToString(), bs.AsBsonDocument["個人資訊"].AsBsonArray[1].AsBsonDocument["Value"].ToString(), bs.AsBsonDocument["個人資訊"].AsBsonArray[2].AsBsonDocument["Value"].ToString());
MessageBox.Show(sResult);
結果:
查詢常用語句:
求文件長度
var bs = coll.FindAll();
string i= bs.Count().ToString();
求文件中陣列長度 var bs = coll.FindOne(Query.EQ("姓名", "趙雲"));
string i = bs.AsBsonDocument["個人資訊"].AsBsonArray.Count().ToString();
文件中是否包含某個元素:
if (bs.AsBsonDocument.Contains("姓名"))
遍歷一個文件中的所有屬性:
var bs = coll_fieldConnect.FindOne(Query.EQ("id", process_id));
StringBuilder sb = new StringBuilder();
foreach (BsonElement d in bs)
{
sb.AppendFormat("{0}:\t{1}\n", d.Name, d.Value);
}
richTextBox1.Text = sb.ToString();
修改資料:
修改按鈕程式碼如下:
MongoClient client;
MongoServer server;
MongoDatabase database;
var conStr = "mongodb://192.168.0.188";
client = new MongoClient(conStr);
server = client.GetServer();
database = server.GetDatabase("test");
var coll = database.GetCollection("student");
BsonDocument bd = new BsonDocument();
bd.Add(new BsonElement("姓名", "趙雲"));
bd.Add(new BsonElement("學號", "002"));
BsonArray ba = new BsonArray();
ba.Add(new BsonDocument { { "Name", "性別" }, { "Value", "男" } });
ba.Add(new BsonDocument { { "Name", "班級" }, { "Value", "1班" } });
ba.Add(new BsonDocument { { "Name", "專業" }, { "Value", "數學" } });
bd.Add(new BsonDocument("個人資訊", ba));
IMongoQuery query = Query.EQ("學號", "002");
coll.Update(query, new UpdateDocument(bd)); MessageBox.Show("修改結束");
結果如下: 轉專業班級成功
刪除資料:
刪除按妞的程式碼如下:
private void button2_Click(object sender, EventArgs e)
{
MongoClient client;
MongoServer server;
MongoDatabase database;
var conStr = "mongodb://192.168.0.188";
client = new MongoClient(conStr);
server = client.GetServer();
database = server.GetDatabase("test");
var coll = database.GetCollection("student");
IMongoQuery query = Query.EQ("學號", "002");
coll.Remove(query);
MessageBox.Show("刪除結束");
}
結果:
刪除成功
2.對mapreduce的操作語法
我們先在mongovue中測試好要用的mapreduce
得到結果為 文件數為1
用c#實現這個功能 按鈕程式碼為:
private void button5_Click(object sender, EventArgs e)
{
MongoClient client;
MongoServer server;
MongoDatabase database;
var conStr = "mongodb://192.168.0.188";
client = new MongoClient(conStr);
server = client.GetServer();
database = server.GetDatabase("test");
var coll = database.GetCollection("student");
BsonJavaScript map = new BsonJavaScript(@"
function map() {
emit(
1,
{count: 1} );
}");
BsonJavaScript reduce = new BsonJavaScript(@"function(key,values){
var total=0;
values.forEach(function(val) {
total += val.count;
});
return total;
};");
var result = coll.MapReduce(map, reduce);
string count = "";
foreach (var s in result.InlineResults)
{
count = s.AsBsonDocument["value"].AsBsonDocument["count"].ToString();
}
MessageBox.Show(count);
}
結果: