meimei10251314 发表于 2015-7-8 06:34:08

mongodb配置及应用实例

  mongodb的文章园中却已不少,看过的文章也已不少,很多东西眼高手低,一直也没有应用过,看的再多,步入实际应用下,虽早已深深知道,但苦于自己懒散...
  练习.练习....做个记录..
  mongbdb是文档型数据库(nosql),可以到http://www.mongodb.org/downloads下载对应版本,这里用的是win下32位的,下载后解压,可以看到bin目录下有很有exe文件,我把文件放到了I盘,并重启名字MongoDB,新建文件夹data(后面会用到),如图

  现在打开命令行窗口并切换到mongo存放目录,mongod启动服务,如图

  这里用到了--dbpath data指定数据文件存放的目录,这就是前面新建的data文件夹,它不会自动创建,如果不指定存放路径(--dbpath data)仅用mongod启动,需要在当前盘符的根目录创建data/db文件夹,它会自动查找,当看到最后的端口号就说明启动成功了!
  当然每次启动都比较麻烦,可以定制成windows服务,我们在data文件夹下创建俩个子文件夹如图

  
  以管理员身份打开命令行窗口并切换到mongodb所在目录,执行命令如图
  

  --directoryperdb说明是否为每一个数据库创建一个文件夹,最后--install安装(注意设置--logpath时要指定一个.log文件,不存在会自动创建)。
  看到 command line via 'net start "MongoDb"'说明定制成功,输入
  net start MongoDB启动服务
  net stop MongoDB停止服务
  sc delete MongoDB删除服务或运行→regedit→注册表编辑器→HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services找到相应服务删除即可
  现在打开http://127.0.0.1:27017/可以看到

  也可以打开http://127.0.0.1:28017/看一些服务端状态信息
  扯了这么多还是直接实例来操作数据库吧,这里我用的是c#驱动,光c#就有很多种,很多人都喜欢用samus驱动,因为支持linq语法,这里也选择此驱动,下载地址https://github.com/samus/mongodb-csharp
  如果下载的直接是.dll文件添加引用即可,如果是源码,编译下在引用.dll即可,目录结构

  Customer



namespace mytest
{
public class Customer
{

public string CustomerID { get; set; }
public string CustomerName { get; set; }

public string Address { get; set; }
}
}

  CustomerBLL



namespace mytest
{
public class CustomerBLL
{
public static void Insert(Customer customer)
{
using (MGHelper mm = new MGHelper())
{
mm.GetCollection().Insert(customer);
}
}
public static void Delete(string customerId)
{
using (MGHelper mm = new MGHelper())
{
mm.GetCollection().Remove(x => x.CustomerID == customerId);
}
}
public static void Update(Customer customer)
{
using (MGHelper mm = new MGHelper())
{
mm.GetCollection().Update(customer, (x => x.CustomerID == customer.CustomerID));
}
}
public static Customer GetById(string customerId)
{
using (MGHelper mm = new MGHelper())
{
return mm.GetCollection().FindOne(x => x.CustomerID == customerId);
}
}
}
}
  MGHelper



namespace mytest
{
public class MGHelper : IDisposable
{
private Mongo _mongo;
private IMongoDatabase _db;
public MGHelper()
: this("Server=127.0.0.1", "test")
{
}

public MGHelper(string connectionString, string dbName)
{
if (string.IsNullOrEmpty(connectionString))
throw new ArgumentNullException("connectionString");
_mongo = new Mongo(connectionString);
_mongo.Connect();
if (string.IsNullOrEmpty(dbName) == false)
_db = _mongo.GetDatabase(dbName);
}
public IMongoDatabase UseDb(string dbName)
{
if (string.IsNullOrEmpty(dbName))
throw new ArgumentNullException("dbName");
_db = _mongo.GetDatabase(dbName);
return _db;
}
public IMongoDatabase CurrentDb
{
get
{
if (_db == null)
throw new Exception("当前连接没有指定任何数据库。请在构造函数中指定数据库名或者调用UseDb()方法切换数据库。");
return _db;
}
}
///
/// 获取当前连接数据库的指定集合【依据类型】
///
///
///
public IMongoCollection GetCollection() where T : class
{
return this.CurrentDb.GetCollection();
}
///
/// 获取当前连接数据库的指定集合【根据指定名称】
///
///
/// 集合名称
///
public IMongoCollection GetCollection(string name) where T : class
{
return this.CurrentDb.GetCollection(name);
}
public void Dispose()
{
if (_mongo != null)
{
_mongo.Dispose();
_mongo = null;
}
}
}
}

  Program演示增加功能



namespace mytest
{
class Program
{
static void Main(string[] args)
{
Customer customer = new Customer();
customer.CustomerID = 1 + "";
customer.CustomerName = "GM0";
customer.Address = "测试";
CustomerBLL.Insert(customer);
customer.CustomerID = 2 + "";
customer.CustomerName = "GM1";
CustomerBLL.Insert(customer);
}

}
}

  这里用了园友的DBHelper操作类,更多详细介绍http://www.iyunv.com/fish-li/archive/2011/06/26/2090800.html
  执行过后如何查看结果呢,mongodb提供了Javascript shell

  相应命令都很直译,就不解释了...
  mongodb的索引



namespace mytest
{
class Program
{
static void Main(string[] args)
{
TestMongodb tm = new TestMongodb();
tm.InsertMongo();
tm.Start();
Console.ReadLine();
}
}
public class TestMongodb
{
private Mongo mongo;
private MongoDatabase mongoDatabase;
private MongoCollection mongoCollection;
public TestMongodb()
{
mongo = new Mongo("mongodb://localhost");
mongoDatabase = mongo.GetDatabase("testDB") as MongoDatabase;
mongoCollection = mongoDatabase.GetCollection("testCollection") as MongoCollection;
mongo.Connect();
}
~TestMongodb()
{
mongo.Disconnect();
}
//插入数据
public void InsertMongo()
{
var random = new Random();
TimeSpan span = new TimeSpan(DateTime.Now.Ticks);
for (int i = 0; i < 100000; i++)
{
Document doc = new Document();
doc["ID"] = i;
doc["Data"] = "data" + random.Next(10000);
mongoCollection.Save(doc);
}
TimeSpan span1 = new TimeSpan(DateTime.Now.Ticks);
string op = string.Format("执行了{0}秒,共插入{1}条数据", span1.Subtract(span).Duration().Seconds, mongoCollection.FindAll().Documents.Count());
Console.WriteLine(op);
}
//删除数据
public void RemoveMongo()
{
mongoCollection.Remove(x => true);
}
//创建索引
public void CreateIndex(string index)
{
mongoCollection.Metadata.CreateIndex(new Document() { { "_" + index + "_", 1 } }, false);
}
//删除索引
public void DropIndex(string index)
{
mongoCollection.Metadata.DropIndex("_" + index + "_");
}
//排序
public void SortForData()
{
mongoCollection.FindAll().Sort(new Document() { { "Data", 1 } });
}
public void Start()
{
Stopwatch watch = new Stopwatch();
watch.Start();
SortForData();
Console.WriteLine("无索引排序时间:" + watch.Elapsed);
CreateIndex("Data");
Stopwatch watch1 = new Stopwatch();
watch1.Start();
SortForData();
Console.WriteLine("有索引排序时间:" + watch1.Elapsed);
}
}
}

  测试截图

  有关索引的说明文章http://www.iyunv.com/lipan/archive/2011/03/28/1997202.html
  关于文件存取的操作参考http://www.iyunv.com/lipan/archive/2011/03/21/1989409.html
  
  
页: [1]
查看完整版本: mongodb配置及应用实例