using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using MongoDB;
namespace TestMongodb
{
public partial class _Default : System.Web.UI.Page
{
//链接字符串
string connectionString = "mongodb://localhost";
//数据库名
string databaseName = "test";
//集合名
string collectionName = "myCollection";
protected void Page_Load(object sender, EventArgs e)
{
//insertData();
//deleteData();
updateData();
QueryAll();
}
private void updateData()
{
//定义Mongo服务
Mongo mongo = new Mongo(connectionString);
//获取databaseName对应的数据库,不存在则自动创建
MongoDatabase mongoDatabase = mongo.GetDatabase(databaseName) as MongoDatabase;
//获取collectionName对应的集合,不存在则自动创建
MongoCollection<Document> mongoCollection = mongoDatabase.GetCollection<Document>(collectionName) as MongoCollection<Document>;
//链接数据库
mongo.Connect();
try
{
Document docFind = mongoCollection.FindOne(new Document { { "ID", 3 } });
docFind["Msg"] = "ssso";
mongoCollection.Update(docFind);
}
finally
{
//关闭链接
mongo.Disconnect();
}
}
public void insertData()
{
//定义Mongo服务
Mongo mongo = new Mongo(connectionString);
//获取databaseName对应的数据库,不存在则自动创建
MongoDatabase mongoDatabase = mongo.GetDatabase(databaseName) as MongoDatabase;
//获取collectionName对应的集合,不存在则自动创建
MongoCollection<Document> mongoCollection = mongoDatabase.GetCollection<Document>(collectionName) as MongoCollection<Document>;
//链接数据库
mongo.Connect();
try
{
//定义一个文档对象,存入一个键值对
Document doc = new Document();
doc["ID"] = 3;
doc["Msg"] = "helloword3!";
//将这个文档对象插入集合
mongoCollection.Insert(doc);
//在集合中查找键值对为ID=1的文档对象
Document docFind = mongoCollection.FindOne(new Document { { "ID", 1 } });
//输出查找到的文档对象中键“Msg”对应的值,并输出
Console.WriteLine(Convert.ToString(docFind["Msg"]));
}
finally
{
//关闭链接
mongo.Disconnect();
}
}
public void deleteData()
{
//定义Mongo服务
Mongo mongo = new Mongo(connectionString);
//获取databaseName对应的数据库,不存在则自动创建
MongoDatabase mongoDatabase = mongo.GetDatabase(databaseName) as MongoDatabase;
//获取collectionName对应的集合,不存在则自动创建
MongoCollection<Document> mongoCollection = mongoDatabase.GetCollection<Document>(collectionName) as MongoCollection<Document>;
//链接数据库
mongo.Connect();
try
{
Document docFind = mongoCollection.FindOne(new Document { { "ID", 1 } });
mongoCollection.Delete(docFind);
}
finally
{
//关闭链接
mongo.Disconnect();
}
}
public void QueryAll()
{
//定义Mongo服务
Mongo mongo = new Mongo(connectionString);
//获取databaseName对应的数据库,不存在则自动创建
MongoDatabase mongoDatabase = mongo.GetDatabase(databaseName) as MongoDatabase;
//获取collectionName对应的集合,不存在则自动创建
MongoCollection<Document> mongoCollection = mongoDatabase.GetCollection<Document>(collectionName) as MongoCollection<Document>;
//链接数据库
mongo.Connect();
try
{
IEnumerable<Document> documents = mongoCollection.FindAll().Documents;
foreach (Document d in documents)
{
Response.Write(d["ID"].ToString() + d["Msg"].ToString() +"<br/>");
}
}
finally
{
//关闭链接
mongo.Disconnect();
}
}
}
}