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 List<Student>()
{
new Student(){ Age = 20, NikeName = "", Sex = true, UserName = "cpg"},
new Student(){ Age = 33, NikeName = "", Sex = false, UserName = "lfd"}
};
MongoCollection<Student> collection = mongodb.GetCollection<Student>() as MongoCollection<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
以上代码仅供参考。