Mongodb的簡單操作方法
MongoDB資料庫屬於一種非關係型的資料庫,對資料的儲存主要是以鍵值對的方式儲存,而且在很大程度上提高了資料的存取時間和效率,簡單總結了下Mongodb的操作方法。
首先我是使用samus驅動實現基本資料操作,在這裡首先下載驅動MongoDB.dll和MongoDB.GridFS.dll。下面是詳細的使用方法,程式碼是從vs裡面直接copy過來的,沒整理,基本都有說明。
Mongo mongo = new Mongo("mongodb://localhost");
MongoDatabase mongodb = mongo.GetDatabase("test") as MongoDatabase
#region 使用泛型類操作
///<summary>
/// Add
///</summary>
///<param name="sender"></param>
///<param name="e"></param>
protected void Button1_Click(object sender, EventArgs e)
{
//新增
List<Student> std = new
{
new Student(){ Age = 20, NikeName = "", Sex = true, UserName = "cpg"},
new Student(){ Age = 33, NikeName = "", Sex = false, UserName = "lfd"}
};
MongoCollection<Student> collection = mongodb.GetCollection<Student
mongo.Connect();
collection.Insert(std);
mongo.Disconnect();
}
///<summary>
/// Get
///</summary>
///<param name="sender"></param>
///<param name="e"></param>
protected void Button2_Click(object sender, EventArgs e)
{
//獲取
MongoCollection<Student> col = mongodb.GetCollection<Student>() as MongoCollection<Student>;
mongo.Connect();
List<Student> list = col.FindAll().Documents.ToList();
//Student std = col.FindOne(p => p.Age == 23);//獲取一個
mongo.Disconnect();
}
///<summary>
/// Edit
///</summary>
///<param name="sender"></param>
///<param name="e"></param>
protected void Button3_Click(object sender, EventArgs e)
{
Student std = new Student() { Sex = false, Age = 100, UserName = "fishangle", NikeName = "" };
MongoCollection<Student> col = mongodb.GetCollection<Student>() as MongoCollection<Student>;
mongo.Connect();
col.Update(std, p => p.UserName == "cpg");//修改匹配到的第一個(從後往前)
List<Student> list = col.FindAll().Documents.ToList();
mongo.Disconnect();
}
///<summary>
/// Del
///</summary>
///<param name="sender"></param>
///<param name="e"></param>
protected void Button4_Click(object sender, EventArgs e)
{
MongoCollection<Student> col = mongodb.GetCollection<Student>() as MongoCollection<Student>;
mongo.Connect();
col.Remove(p => p.Sex == true);//刪除指定的(匹配的都將刪除)
//col.Remove(x => true);//刪除全部
mongo.Disconnect();
}
#endregion
#region 一般操作 (一般操作在獲取集合時必須有一個預設的CollectionName
///<summary>
/// Add
///</summary>
///<param name="sender"></param>
///<param name="e"></param>
protected void Button5_Click(object sender, EventArgs e)
{
MongoCollection<Document> col = mongodb.GetCollection<Document>("mongoCollection") as MongoCollection<Document>;
mongo.Connect();
#region 單個插入
Document doc = new Document();
doc["Id"] = 1;
doc["name"] = "池鵬剛";
col.Insert(doc);
#endregion
#region 多個插入
List<Document> list = new List<Document>()
{
new Document(){{"Id",1},{"name","cpg1"}},
new Document(){{"Id",2},{"name","cpg2"}},
new Document(){{"Id",3},{"name","cpg3"}}
};
col.Insert(list);
List<Document> dtAll = col.FindAll().Documents.ToList();
#endregion
mongo.Disconnect();
}
///<summary>
/// get
///</summary>
///<param name="sender"></param>
///<param name="e"></param>
protected void Button6_Click(object sender, EventArgs e)
{
MongoCollection<Document> col = mongodb.GetCollection<Document>("mongoCollection") as MongoCollection<Document>;
mongo.Connect();
List<Document> dtAll = col.FindAll().Documents.ToList();
var dtOne = col.FindOne(new Document() { { "Id", 1 } });//發現id為1的doc
var name = dtOne["name"];//取出此doc中的name值
mongo.Disconnect();
}
///<summary>
/// del
///</summary>
///<param name="sender"></param>
///<param name="e"></param>
protected void Button8_Click(object sender, EventArgs e)
{
MongoCollection<Document> col = mongodb.GetCollection<Document>("mongoCollection") as MongoCollection<Document>;
mongo.Connect();
List<Document> dtAll = col.FindAll().Documents.ToList();
//col.Remove(p => true);//刪除全部
col.Remove(new Document() { { "Id", 1 } });//匹配的都將刪除
List<Document> dtAlls = col.FindAll().Documents.ToList();
mongo.Disconnect();
}
///<summary>
/// update
///</summary>
///<param name="sender"></param>
///<param name="e"></param>
protected void Button7_Click(object sender, EventArgs e)
{
MongoCollection<Document> col = mongodb.GetCollection<Document>("mongoCollection") as MongoCollection<Document>;
mongo.Connect();
List<Document> dtAll = col.FindAll().Documents.ToList();
Document doc = new Document();
doc["Id"] = 1;
doc["name"] = " 曉風殘月";
col.Update(doc, new Document() { { "Id", 1 } });
List<Document> dtAlls = col.FindAll().Documents.ToList();
mongo.Disconnect();
}
#endregion
#region 檔案操作
protected void Button9_Click(object sender, EventArgs e)
{
string fileName = FileUpload1.FileName;
byte[] byteFile = FileUpload1.FileBytes;
Stream stream = FileUpload1.FileContent;
string name = Guid.NewGuid().ToString();
//這裡GridFile建構函式有個過載,bucket引數就是用來替換那個建立集合名中預設的"fs"的。
mongo.Connect();
GridFile gridFile = new GridFile(mongodb, "img");
using (GridFileStream gridFileStream = gridFile.Create(fileName))
{
gridFileStream.Write(byteFile, 0, byteFile.Length);
}
mongo.Disconnect();
}
protected void Button10_Click(object sender, EventArgs e)
{
string filename = "圖片1.jpg";
mongo.Connect();
GridFile gridFile = new GridFile(mongodb, "img");
GridFileStream gridFileStream = gridFile.OpenRead(filename);
byte[] bytes = new byte[gridFileStream.Length];
gridFileStream.Read(bytes, 0, bytes.Length);
mongo.Disconnect();
}
#endregion
#region 索引
protected void Button12_Click(object sender, EventArgs e)
{
#region 新增索引
// 1. 預設索引
//MongoDB有個預設的“_id”的鍵,他相當於“主鍵”的角色。集合建立後系統會自動建立一個索引在“_id”鍵上,
//它是預設索引,索引名叫“_id_”,是無法被刪除的。我們可以通過以下方式檢視:
MongoCollection<Document> mongoCollection = mongodb.GetCollection<Document>("mongoCollection") as MongoCollection<Document>;
mongo.Connect();
var _idIndex = mongoCollection.Metadata.Indexes.Single(x => x.Key == "_id_");
Console.WriteLine(_idIndex);
// 2. 單列索引
//在單個鍵上建立的索引就是單列索引,例如我們要在“UserInfo”集合上給“UserName”鍵建立一個單列索引,語法如下:(1表示正序,-1逆序)
mongoCollection.Metadata.CreateIndex(new Document { { "name", 1 } }, false);
//接著,我們用同樣方法查詢名為“_UserName_”的索引
var _UserName_Index = mongoCollection.Metadata.Indexes.Single(x => x.Key == "_name_");
Console.WriteLine(_UserName_Index);
// 3.組合索引
//另外,我們還可以同時對多個鍵建立組合索引。如下程式碼建立了按照“UserId”正序,“UserName”逆序的組合索引:
mongoCollection.Metadata.CreateIndex(new Document { { "Id", 1 }, { "name", -1 } }, false);
// 4.子文件索引
// 我們可以對文件型別的鍵建立各種索引,例如單列索引,如下建立使用者詳細資訊“Detail”的單列索引:
mongoCollection.Metadata.CreateIndex(new Document { { "Detail", 1 } }, false);
//對子文件的鍵建立組合索引:例如在“Detail.Address”和“Detail.Age”上建立組合索引:
mongoCollection.Metadata.CreateIndex(new Document { { "Detail.Address", 1 }, { "Detail.Age", -1 } }, false);
// 5.唯一索引
// 唯一索引限制了對當前鍵新增值時,不能新增重複的資訊。值得注意的是,當文件不存在指定鍵時,會被認為鍵值是“null”,
//所以“null”也會被認為是重複的,所以一般被作為唯一索引的鍵,最好都要有鍵值對。
// 對“UserId”建立唯一索引(這時候最後一個引數為“true”):
mongoCollection.Metadata.CreateIndex(new Document { { "UserId", 1 } }, true);
#endregion
#region 得到索引
var allIndex = mongoCollection.Metadata.Indexes;//獲取所有索引
#endregion
#region 刪除索引
var listIndexes = mongoCollection.Metadata.Indexes.ToList();//得到所有索引
for (int i = 0; i < listIndexes.Count; i++)
{
if (listIndexes[i].Key != "_id_")
{
mongoCollection.Metadata.DropIndex(listIndexes[i].Key);
}
}
#endregion
}
protected void Button13_Click(object sender, EventArgs e)
{
Mongo mg = new Mongo("mongodb://localhost");
MongoDatabase mongoIndex = mg.GetDatabase("mongoIndex") as MongoDatabase;
MongoCollection<Document> col = mongoIndex.GetCollection<Document>("indexCollection") as MongoCollection<Document>;
mg.Connect();
col.Insert(getList());
mg.Disconnect();
}
///<summary>
///初始化集合
///</summary>
///<returns></returns>
public List<Document> getList()
{
List<Document> docList = new List<Document>();
for(int i=0;i<10000;i++)
{
docList.Add(new Document() { { "ID", i }, { "Class", "grade" + i }, { "std", new Student() { UserName = "user" + i, Age = i + 20, NikeName = "", Sex = (i % 2 == 0 ? true : false) } } });
};
return docList;
}
protected void Button14_Click(object sender, EventArgs e)
{
Mongo mg = new Mongo("mongodb://localhost");
MongoDatabase mongoIndex = mg.GetDatabase("mongoIndex") as MongoDatabase;
MongoCollection<Document> col = mongoIndex.GetCollection<Document>("indexCollection") as MongoCollection<Document>;
mg.Connect();
col.Metadata.CreateIndex(new Document { { "ID", 1 }, { "Class",1 } }, false);//加入索引 1表示正序 -1表示逆序
Stopwatch sw = new Stopwatch();
sw.Start();
List<Document> docList = col.FindAll().Documents.ToList();
sw.Stop();
mg.Disconnect();
Label1.Text = sw.ElapsedMilliseconds.ToString();
}
protected void Button15_Click(object sender, EventArgs e)
{
Mongo mg = new Mongo("mongodb://localhost");
MongoDatabase mongoIndex = mg.GetDatabase("mongoIndex") as MongoDatabase;
MongoCollection<Document> col = mongoIndex.GetCollection<Document>("indexCollection") as MongoCollection<Document>;
mg.Connect();
//col.Metadata.CreateIndex(new Document { { "ID", 1 } }, false);
Stopwatch sw = new Stopwatch();
sw.Start();
List<Document> docList = col.FindAll().Documents.ToList();
sw.Stop();
mg.Disconnect();
Label2.Text = sw.ElapsedMilliseconds.ToString();
}
protected void Button16_Click(object sender, EventArgs e)
{
Mongo mg = new Mongo("mongodb://localhost");
MongoDatabase mongoIndex = mg.GetDatabase("mongoIndex") as MongoDatabase;
MongoCollection<Document> col = mongoIndex.GetCollection<Document>("indexCollection") as MongoCollection<Document>;
mg.Connect();
Label3.Text = "";
foreach (var index in col.Metadata.Indexes)//col.Metadata.Indexes 獲取所有索引
{
Label3.Text += index+"<br/>";
}
}
#endregion
以上程式碼僅供參考。